Stackoverflow 编辑器 url 替换 php

Stackoverflow editor url replacement in php

我正在尝试模拟类似于 Whosebug 编辑器行为的行为来替换 php 中的文本和 url。我很难找到正确的正则表达式或正确的模拟方法。

sample text

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

expected result

我们有 first url and the second url and then the third url.

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

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

正则表达式 live demo here

细分:

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

并且以下匹配末尾的索引:

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

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

$re = '/\[@url\|([^|]+)\|(\d+)\](?=(?>.*\R+)+^\[]:\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