PHP 中的 preg_replace() - 当跟随新行时,将一个字符的 n 次出现替换为另一个字符的 n 次出现
我正在寻找替换新行后面出现的所有空格字符(或出现在输入字符串开头的空格字符)。我知道我可以使用 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"
I'm looking to replace all occurrences of space characters that follow a new line (or occur at the beginning of the input string). I know that I can achieve this using preg_replace_callback() with a callback that uses str_repeat and strlen, or similarly with the /e switch; but was wondering if it could be done more simply.
Currently I have the following:
$testData = " Hello\n to everybody\n in the world";
echo preg_replace('/^|\n( )+/', ' ', $pValue);
which gives:
" Hello to everybody in the world"
What I'm really after is:
" Hello\n to everybody\n in the world"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在提问之前我应该更努力地搜索:找到了似乎完美工作的答案(针对 java 解决方案)。为了其他有同样问题的人,我将把解决方案留在这里。
现在只需要确定旧版本的 PHP 是否支持这一点。
I should have searched harder before asking: found the answer (for a java solution) that seems to work perfectly. I'll leave the solution here for the sake of anybody else that has the same problem.
Now just need to identify whether older versions of PHP support this.
您可以使用递归
You can use recursion