PHP中的Stackoverflow编辑器URL替换

时间:2019-01-09 05:55:02

标签: php regex preg-replace

我正在尝试模拟类似于stackoverflow编辑器的行为,以替换php中的文本和url。我在寻找正确的正则表达式或模拟此方法的方法时遇到了麻烦。

  

示例文字

We have [@url|first url|1] and 
the [@url|the second url|2] and then [@url|the third url|3]

[1]: https://www.google.com
[2]: www.facebook.com 
[3]: http://www.amazon.com
  

预期结果

我们有first urlthe second url,然后是the third url

1 个答案:

答案 0 :(得分:3)

以下正则表达式捕获必需的部分,例如文本和URL:

\[@url\|([^|]+)\|(\d+)\](?=(?>.*\R+)+^\[\2]:\s+(\S+))

正则表达式live demo here

故障:

  • \[@url\|([^|]+)\|(\d+)\]匹配一个@url块并捕获文本和索引
  • (?=开始积极向前
    • (?>原子(非捕获)组的开始
      • .*\R+匹配一行及其后面的换行符
    • )+组结束,至少重复一次
    • ^\[\2]:\s+(\S+)根据上面捕获的索引号匹配索引并捕获URL
  • )正向超前结束

和以下匹配索引结尾:

^\[\d+]:\h+\S+

所以在这里,我们将使用preg_replace_callback将这些块替换为其相应的锚标记并删除索引:

$re = '/\[@url\|([^|]+)\|(\d+)\](?=(?>.*\R+)+^\[\2]:\s+(\S+))|^\[\d+]:\h+\S+/m';
echo preg_replace_callback($re, function($match) {
    if (isset($match[1])) {
        return "<a href=\"{$match[3]}\">{$match[1]}</a>";
    }
}, $str);

PHP live demo here