简体   繁体   中英

Regex of non breaking space in php

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.

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 + .

$s = preg_replace('~(?<= ) ~', '\xc2\xa0', $s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM