tags:

views:

234

answers:

2

input:

$string = "a b c  d   e"; 

i have a string in php and I need to replace the string with the non-break space code

output:

"a \xc2\xa0b c \xc2\xa0d \xc2\xa0\xc2\xa0e"
  1. single space and the first space is not allowed to replace with \xc2\xa0
  2. when two space appear " ", the output is " \xc2\xa0", first space is kept and the second space is replace.
  3. when three spaces appear " ", the output is " \xc2\xa0\xc2\xa0", first space is kept and the second and third space is replaced.
  4. the input string is randomly

Any idea with the Regular expression or other function of php Thank you very much.

A: 
preg_replace('/(?<= ) {1,2}/', "\xc2\xa0", $str);

Lookbehind (?<= ) sees if a space is preceeding the match,  {1,2} matches 1 and 2 spaces. The replace will only happen with the spaces matched, not the lookbehind. If you want to replace as many spaces as possible (if there are more than 3 also), just replace {1,2} with +.

Tor Valamo
thanks, tor, very good explanation of (?<=)
brian
+1  A: 
$s = preg_replace('~(?<= ) ~', '\xc2\xa0', $s);
Max Shawabkeh
thank max, it work
brian