【问题标题】:PHP: Count number of spaces in a multiple space spanPHP:计算多个空格跨度中的空格数
【发布时间】:2017-08-05 04:01:24
【问题描述】:

我正在扫描表单字段条目 ($text) 中的空格并使用 preg_replace 将空格替换为空白点。

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

这很好用,除非一行中有多个连续的空格。它们都被视为空白。

如果我知道会有多少空格,我可以使用它:

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

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

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.

我将如何扫描输入中的连续空格、计算它们并将该计数设置为一个变量以放置在多个空格的 preg_replace 语句中?

或者有没有我明显想念的另一种方法?

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

【问题讨论】:

  • 您的预期结果是什么?
  • 如果您尝试删除单个空格的多个空格,那么preg_match('/\s+/', ' ', $string) 将用单个空格替换任意数量的空格。如果您试图保留多个空格以实际显示为多个空格,请将它们保留并使用 <pre> 标记(或 css white-space 属性)来保留空格。
  • 对你的第一个问题:你可以使用preg_replace_callback()所以如果你找到3个空格你可以在回调中添加3个*

标签: php count preg-replace space


【解决方案1】:

如果你想用单个空格替换多个空格,你可以使用

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

【讨论】:

    【解决方案2】:

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

    $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)
    )
    

    【讨论】:

      【解决方案3】:

      使用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.

      【讨论】:

      • 谢谢。我在尝试使用 nbsp 和自动换行时仍然遇到问题,但那是因为 HTML 只是折叠了大的空白区域。那完全是另一个问题。这让我得到了我需要的东西。非常感谢。
      猜你喜欢
      • 2012-03-06
      • 2014-04-10
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 2013-07-03
      相关资源
      最近更新 更多