PHP:计算多个 space 跨度中 space 的数量

PHP: Count number of spaces in a multiple space span

我正在扫描 space 的表单字段条目 ($text) 并使用 preg_replace.[=19 将 space 替换为空白点=]

$text=preg_replace('/\s/',' ',$text);

这很好用,除非一行中有多个连续的 space。都当做空白处理。

如果我知道 space 的数量,我可以使用它:

$text=preg_replace('/ {2,}/','**' ,$text);

但是我永远无法确定输入可能有多少 space。

Sample Input 1: This is a test.
Sample Input 2: This  is a test.
Sample Input 3: This                    is a test.

使用上面的两个 preg_replace 语句我得到:

Sample Output 1: This is a test.
Sample Output 2: This**is a test.
Sample Output 3: This**is a test.

我将如何扫描连续 space 的输入,对它们进行计数并将该计数设置为一个变量以放置在多个 space 的 preg_replace 语句中?

或者是否有另一种我显然想念的方法?

*注意:使用   进行替换可以维持额外的 space,但我无法将 space 替换为  。当我这样做时,它会在我的输出中打破自动换行,并在换行发生的任何地方打破单词,因为字符串永远不会结束,它只会在任何时候换行,而不是在单词之前或之后换行。

如果你想用单个 space 替换多个 space 你可以使用

$my_result =  preg_replace('!\s+!', ' ', $text);

使用preg_replace_callback计算找到的空间。

$text = 'This  is a test.';

print preg_replace_callback('/ {1,}/',function($a){
     return str_repeat('*',strlen($a[0]));
},$text);

结果:This**is*a*test.

您可以使用两个环视的交替来检查前后是否有空格:

$text = preg_replace('~\s(?:(?=\s)|(?<=\s\s))~', '*', $text);

demo

详情:

\s  # a whitespace
(?:
    (?=\s)     # followed by 1 whitespace
  | # OR
    (?<=\s\s)  # preceded by 2 whitespaces (including the previous)
)