Cannt get my head around this at all, i need to search a string for a word, and then replace it with another based on an array, the problem being is the word is the same throught so i need to loop through itsome how. $new_words =array("NewWord1", "NewWord2","NewWord3") ///etc $needle ="{This}"; $haystack = "My string include {This} and {This} and finally ends in this {This}" I need to replace the needle with the new_words I can count the times it occurs and now how to subsrt_replace, but cannt seem to set any offsets or loop for each occurence Any help would save me a late night???
This should work for you: http//: us3.php.net/manual/en/function.preg-replace.php http//: us3.php.net/manual/en/function.preg-match-all.php (grr... can't link yet.) $new_words[0] = 'NewWord0'; $new_words[1] = 'NewWord1'; $new_words[2] = 'NewWord2'; $new_words[3] = 'NewWord3'; $new_words[4] = 'NewWord4'; $new_words[5] = 'NewWord5'; $needle = '(this)'; //Make sure to include delimiters (in this case ( and ), but any non-alpha/numeric character will work $haystack = 'this is some text that will have this replaced 3 times. this should work!'; $limit = 1; //limits the maximum number of replacements for $needle in $haystack preg_match_all($needle, $haystack, $matches); $total = count($matches[0]); //How many matches for($i = 0; $i < $total; $i++) //Loop through and replace as necessary $haystack = preg_replace($needle, $new_words[$i], $haystack, $limit); Code (markup): -the mole