PHP中的preg_replace()-当跟随新行时,将一个字符的n次出现替换为另一个字符的n次出现
我希望替换所有出现在新行后面或输入字符串开头的空格字符。我知道我可以使用preg_replace_回调来实现这一点,回调使用str_repeat和strlen,或者类似地使用/e开关;但我想知道是否可以做得更简单一些 目前我有以下几点:PHP中的preg_replace()-当跟随新行时,将一个字符的n次出现替换为另一个字符的n次出现,php,regex,preg-replace,Php,Regex,Preg Replace,我希望替换所有出现在新行后面或输入字符串开头的空格字符。我知道我可以使用preg_replace_回调来实现这一点,回调使用str_repeat和strlen,或者类似地使用/e开关;但我想知道是否可以做得更简单一些 目前我有以下几点: $testData = " Hello\n to everybody\n in the world"; echo preg_replace('/^|\n( )+/', ' ', $pValue); 其中: " He
$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"
可以使用递归
$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;
}
在提问之前,我应该更努力地搜索:找到一个似乎工作完美的java解决方案的答案。为了其他有同样问题的人,我将把解决方案留在这里
$testData = " Hello\n to everybody\n in the world";
echo preg_replace('/(?m)(?:^|\\G) /', ' ', $pValue);
现在只需要确定旧版本的PHP是否支持此功能。旧了多少?preg_*函数始终由PCRE库提供支持,根据其changelog,PCRE自2003年2月4.0版起就支持\G。ref:@Alan-我对\G操作符一点也不熟悉,并且知道随着时间的推移,PHP引入了对许多新regexp元素/开关的访问。这是为了在开源库中提高性能:我主要关注5.2.0,我通常不会提供更早版本的支持,但我知道库的一些用户早在5.1.6版本就开始使用PHP