我只需匹配"空格"出现在分隔符[]内,所以我可以用$更改空格。
以下是文字:
[编辑]表达式& [查看匹配的文字]。滚动[匹配或 表达式的细节。使用ctrl-z撤消错误。 [保存 收藏夹和与朋友分享表达]或社区。 使用工具探索您的结果。 [完整的参考和帮助是 在图书馆中可用或观看视频教程]。
这是我的正则表达式模式:
$pattern = preg_replace('/(?!\[[a-z]+)( )(?=[a-z]+\])/','$',$newString);
我使用regexr.com来测试我的模式。该模式的输出如下所示:
我如何仅匹配"空格"出现在分隔符[]中谢谢。
答案 0 :(得分:4)
您可以使用
(?:\G(?!\A)|\[)[^]\s]*\K\s+
请参阅regex demo
<强>详情:
(?:\G(?!\A)|\[)
- 上一次成功匹配(\G(?!\A)
)或(|
)[
符号[^]\s]*
- 除]
和空格\K
- 匹配重置操作符,省略当前迭代中到目前为止匹配的所有文本\s+
- 1+空格$str = '[Edit the] Expression & [Text to see matches]. Roll [over matches or the] expression for details. Undo mistakes with ctrl-z. [Save Favorites and Share expressions with friends] or the Community. Explore your results with Tools. [A full Reference and Help is available in the Library or watch the video Tutorial].';
$result = preg_replace('~(?:\G(?!\A)|\[)[^]\s]*\K\s+~', '$', $str);
echo $result;
另一种方法:匹配[...]
子字符串(使用\[[^][]+]
模式)并仅将匹配内的空格替换为preg_replace_callback
:
$result = preg_replace_callback('~\[[^][]+]~', function ($m) {
return preg_replace('~\s+~', '$', $m[0]);
}, $str);
请参阅another PHP demo。