简体   繁体   English

php中不间断空间的正则表达式

[英]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 我在php中有一个字符串,我需要用不间断空格代码替换该字符串

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 单个空格,不允许将第一个空格替换为\\ xc2 \\ xa0
  2. when two space appear " ", the output is " \\xc2\\xa0", first space is kept and the second space is replace. 当出现两个空格“”时,输出为“ \\ xc2 \\ xa0”,第一个空格被保留,第二个空格被替换。
  3. when three spaces appear " ", the output is " \\xc2\\xa0\\xc2\\xa0", first space is kept and the second and third space is replaced. 当出现三个空格“”时,输出为“ \\ xc2 \\ xa0 \\ xc2 \\ xa0”,将保留第一个空格,并替换第二个和第三个空格。
  4. the input string is randomly 输入字符串是随机的

Any idea with the Regular expression or other function of php Thank you very much. 与正则表达式或php的其他功能有关的任何想法非常感谢。

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

Lookbehind (?<= ) sees if a space is preceeding the match, {1,2} matches 1 and 2 spaces. 从后面(?<= )看是否在空格前面, {1,2}匹配1和2个空格。 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 + . 如果要替换尽可能多的空格(如果还多于3个空格),只需将{1,2}替换为+

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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