I have a string in which I want to replace a series of substrings. I then have an array of strings, each of which represents one substring I want to replace. I have a second array of strings, where each element represents what I want to replace the substring with. Hopefully that is clear.

Unfortunately, str_replace does not work, as it takes the first search string and the first replacement string, and goes through the whole string replacing each substring that matches the search string with the replacement string. Of course, this is exactly as str_replace is documented. However, the behavior I want is to replace the first substring with the replacement string, then move to the next serach string and the next replacement string and continue ...

preg_replace seems to imply it will do that if you include the limit variable. I tried that, but unfortunately, it complained about my string ... the sting contains essentially HTML.

any ideas?

thanks,
ron

    go thru the list and call each replacement function in turn?

      unfortunately, the strings to be replaced aren't unique, so using str_replace one at a time won't work. i wrote a loop that locates the first substring, replaces it, advances the string pointer past the substring, and then finds the next substring and so one ... i was hoping I could use a php function - i wish str_replace had an option to operate like this .... oh well....
      r

        sounds like you need to research Regular Expressions... there are two types, identical outcome, different syntax, ereg and preg functions

        this lets you set patterns in the string to replace, however if you are doing straight string for string replacements im sure str_replace is what you want

        http://www.php.net/manual/en/ref.regex.php

        phpbuilder here has a tutorial:
        http://www.phpbuilder.com/columns/dario19990616.php3

        though... you should not use two arrays, but one array if at all possible

        replace this

        $to_replace = array( 'a', 'b', 'c' );
        $replace_with = array( 'A', 'B', 'C' );
        

        with this

        $replacements = array( 'a'=>'A', 'b'=>'B', 'c'=>'B' );
        

          Originally posted by rharter
          but unfortunately, it complained about my string ... the sting contains essentially HTML.

          Complained how? My guess is that you either didn't put your search string in a pair of / characters, and/or didn't preg_quote the string first.

            Write a Reply...