Link 在使用 preg_replace 时被替换不是预期的方式

Link being replaced not expected way when using preg_replace

我有一个带有正则表达式的 array,我使用 preg_replace:[=20= 将 URL's/hashtags 替换为 links ]

$regs = array('!(\s|^)((https?://|www\.)+[a-z0-9_./?=;&#-]+)!i', '/#(\w+)/');
$subs = array(' <a href="" target="_blank"></a>', '<a href="/hashtag/" title="#">#</a>');

$output = preg_replace($regs, $subs, $content);

如果$content有一个link,例如:https://www.google.com/,它会正确替换;如果文本后面有一个标签,例如:#hello 也替换,但是,如果有一个带有标签的 link,例如:https://www.google.com/#top 替换如下:

#top" target="_blank">https://www.google.com/#top
^^^^                                         ^^^^

只有高亮部分变成links.

如何修复?

这是因为你数组中的第二个正则表达式也匹配字符串中 # 之后的部分。

将您的正则表达式更改为:

$regs = array('!(\s|^)((https?://|www\.)+[a-z0-9_./?=;&#-]+)!i', '/(?<=[\'"\s]|^)#(\w+)/');
$subs = array(' <a href="" target="_blank"></a>', '<a href="/hashtag/" title="#">#</a>');
$content = 'https://www.google.com/#top foobar #name';

# now use in preg_replace
echo preg_replace($regs, $subs, $content);

它会给你:

<a href="https://www.google.com/#top" target="_blank">https://www.google.com/#top</a> foobar <a href="/hashtag/name" title="#name">#name</a>