String searching and replacing

Discussion in 'PHP' started by Big 'G', Jan 23, 2006.

  1. #1
    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:confused:
    Any help would save me a late night???:D
     
    Big 'G', Jan 23, 2006 IP
  2. themole

    themole Peon

    Messages:
    82
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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
     
    themole, Jan 23, 2006 IP
    mitchandre and forkqueue like this.