Sunday 15 April 2012

php - String replace first occurence of a needle, ignore others -


I want to do a str_replace as if it changes the first needle (out of an array of needle) and the rest

 ); $ Place = array ('1', '2'); $ Mystring = "this is # b # is #b # one test # one # string";   

I have to parse $ mystring so that it is output:

  $ mystring = "this is a test string 2";   

The first needle discovered then follows the rule shown in the replacement array, and all subsequent needles are replaced with an empty string.

Hope is understood, it is difficult to explain my thoughts in words.

I have found a great solution for you (even faster), there is no loop required: / P>

  $ replace = array (// this will make your life really easy "# a #" => 1, "#b #" => 2); $ Pattern = "/ (". "," $ "," $ String " $ String, $ matches); $ String = preg_replace ("/ {$ matches [0] [0]} /", "{$ matches [$ matches [0] [0]]}", $ string, 1; $ String = preg_replace ($ pattern, "", $ string); resonance $ string;    

No comments:

Post a Comment