【问题标题】:preg_replace() in PHP - Replacing n-occurrences of a character with n-occurrences of another, when following a new linePHP 中的 preg_replace() - 跟随一个新行时,将一个字符的 n 次出现替换为另一个字符的 n 次出现
【发布时间】:2010-11-17 14:28:47
【问题描述】:

我希望替换所有出现在新行之后的空格字符(或出现在输入字符串的开头)。我知道我可以使用 preg_replace_callback() 和使用 str_repeat 和 strlen 的回调来实现这一点,或者类似地使用 /e 开关;但想知道是否可以更简单地完成。

目前我有以下:

$testData = "  Hello\n to everybody\n   in the world";
echo preg_replace('/^|\n( )+/', ' ', $pValue);

给出:

"   Hello to everybody in the world" 

我真正追求的是:

"  Hello\n to everybody\n   in the world" 

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    在问之前我应该​​更加努力地搜索:找到似乎完美工作的答案(对于 java 解决方案)。为了其他有同样问题的人,我将把解决方案留在这里。

    $testData = "  Hello\n to everybody\n   in the world"; 
    echo preg_replace('/(?m)(?:^|\\G) /', ' ', $pValue); 
    

    现在只需要确定旧版本的 PHP 是否支持这个。

    【讨论】:

    • 几岁? preg_* 函数一直由 PCRE 库提供支持,根据其变更日志,PCRE 自 2003 年 2 月 4.0 版起支持 \G。参考:pcre.org/changelog.txt
    • @Alan - 我根本不熟悉 \G 运算符,并且知道 PHP 随着时间的推移引入了对许多新的正则表达式元素/开关的访问。这是为了提高性能,在一个开源库中:我主要关心 5.2.0(我通常不会提供更早的支持),但知道该库的一些用户正在使用 PHP 版本早在 5.1.6
    【解决方案2】:

    你可以使用递归

    $pValue = "  Hello\n to everybody\n   in the world";
    echo myReplace($pValue);
    
    function myReplace($value)
    {
        $value = preg_replace('/(^|\\n)(( )*) /', '\1\2 ', $value);
        if (preg_match('/(^|\\n)(( )*) /', $value))
        {
            $value = myReplace($value);
        }
        return $value;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 1970-01-01
      • 2018-06-04
      • 2014-10-27
      • 2022-01-13
      • 1970-01-01
      • 2011-12-19
      • 2014-06-13
      • 2022-12-04
      相关资源
      最近更新 更多