PHP - Replace the string as normal and reverse only once -


i need replace each word once, , vice versa. taht, used code not work, , can not find answer question.

input:

hello w1 w2 w12 new1 new12 new2

expected output:

hello new1 new2 w12 w1 new12 w2

i need words / phrases text replace.

w1 replace new1

w12 unchanged

w2 replace new2

new1 replace w1

new12 unchanged

new2 replace w2

of course text in persian

my code is:

$string="hello w1 w2 w12 new1 new12 new2";  $fword= array("w1","w2"); $lword= array("new1","new2");  $cnt=0; $string=str_replace($fword,$lword,$string,$cnt); $string=str_replace($lword,$fword,$string,$cnt); echo "<h2>change in string: $cnt <br> new string: $string </h2>"; 

but wrong

i use code:

$string="hello w1 w2 w12 new1 new12 new2";  $fword= array("w1","w2","new1","new2"); $lword= array("new1","new2","w1","w2");  $cnt=0; $string=str_replace($fword,$lword,$string,$cnt); echo "<h2>change in string: $cnt <br> new string: $string </h2>"; 

you should use preg_replace. tell check space or string beginning or end (^|.*\s)and (\s.*|$) avaid replacing partial matches.

$string="hello w1 w2 w12 new1 new12 new2";  $replacements = array(     "w1" => "new1",     "w2" => "new2",     "new1" => "w1",     "new2" => "w2" );  foreach ($replacements $from=>$to) {     $string = preg_replace(                 '/(^|.*\s)'.preg_quote($from).'(\s.*|$)/',                 '\1'.preg_quote($to).'\2',                  $string); }  echo $string; 

if first occurrenc should replaced can give function limit of 1 4th parameter.

update: detailed explanation

(^|.*\s): first match group: string begins, or start of string followed space.

preg_quote($from): string replace. quoted support allkind of characters. preg_quote() escape characters not interfere regular expression control codes. takes care of unicode characters.

(\s.*|$): second match group: end of string or space followed rest of string.

'\1'.preg_quote($to).'\2': replacement. first group + new string + second group.

update 2:

got rid of unneccessary group in code , added escaping more general applyable kinds of inputs.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -