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