【问题标题】:Matching String Wrapped In Symbol For Regex Replace匹配字符串包裹在符号中以进行正则表达式替换
【发布时间】:2021-01-05 13:04:59
【问题描述】:

我正在尝试弄清楚如何在我的 WordPress 博客上实现 Regex。

问题

我想用一些内联样式替换某些内容,我正在使用正则表达式来完成此操作。

我的想法如下:找到包裹在特定符号中的字符串,即“~string~”,然后将其动态替换为具有特定类的span。

我将寻求与 SO 的内联 code 突出显示功能类似的效果,但我没有使用反引号,而是使用“~”作为我的选择符号(因为 WordPress 已经将“`”标识为代码)。

快速示例

原文

This is a demo paragraph with a wrapped string ~here~, with another string ~~here~~.

正则表达式替换后

This is a demo paragraph with a wrapped string <span class="classOne">here</span>, with another string <span class="classTwo">here</span>.

我正在努力解决的问题

我正在使用的正则表达式是这样的:/~(.*?)~/,它可以很好地查找诸如“~demo~”之类的字符串,但我不确定如何将其扩展为能够查找具有多个分隔符的字符串,例如:“~~demo~~”。

对我来说棘手的部分是它需要区分只有一个“~”和其中两个,因为我想为每个结果分配不同的替换。

任何帮助将不胜感激!提前致谢。

【问题讨论】:

  • 这不是问题,只是使用交替,~~([\s\S]*?)~~|~([^~]*)~。然后根据需要处理每个捕获。
  • 或者,~~([\s\S]*?)~~(?!~)|~([^~]*)~
  • 太棒了,非常感谢您的提示!
  • 请查看my answer

标签: regex wordpress syntax-highlighting


【解决方案1】:

你可以使用

~~([\s\S]*?)~~(?!~)|~([^~]*)~

请参阅regex demo。详情:

  • ~~([\s\S]*?)~~(?!~) - ~~,然后是匹配任何零个或多个字符但尽可能少的捕获组 #1,然后是 ~~ 子字符串后面不跟另一个 ~ 字符
  • | - 或
  • ~([^~]*)~ - 一个~,然后是匹配除~ 之外的零个或多个字符的捕获组#2,然后是~

如果您在 PHP 中使用它,您可以使用带有 preg_replace_callback 的模式,您可以在匹配特定捕获组时定义单独的替换逻辑。

PHP demo

$html = 'This is a demo paragraph with a wrapped string ~here~, with another string ~~here~~.';
echo preg_replace_callback('/~~([\s\S]*?)~~(?!~)|~([^~]*)~/', function ($m) {
    return !empty($m[1]) ? '<span class="classTwo">' . $m[1] . '</span>' : '<span class="classOne">' . $m[2] . '</span>';
},$html);
// => This is a demo paragraph with a wrapped string <span class="classOne">here</span>, with another string <span class="classTwo">here</span>.

【讨论】:

  • 这正是我想要的,非常感谢!我是 PHP 新手,所以我没有意识到我可以以这种方式使用 preg_replace_callback()。再次感谢!
【解决方案2】:

为了让它更通用一点,你可以试试这个 (~+)([^~]+?)(~+)。这将需要对匹配 (~) 的第一个或第三个分组中存在的字符数进行额外检查。根据字符数在代码中决定 classOne、classTwo、classThree 等...

【讨论】:

  • 太好了,我也试试。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多