PHP Preg Replace 在换行后不起作用

PHP Preg Replace doesn't work AFTER line break

拥有获取 txt 文件、替换换行符、链接和主题标签的代码。

当主题标签跟在换行符之后时,它不会替换主题标签。不确定在正则表达式中哪里失败了。

// replace line breaks
$txt = str_replace('&lt;br /&gt;','<br />',$txt);

// replace links
$txt = preg_replace_callback('@(https?://([-\w\.]+)+(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?)@', function($m) { return '<a href="'.$m[1].'" target="_blank">'.substr($m[1], 0, 30).'...</a>'; }, $txt);

// replace hashtags
$txt = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/m', '<a href="index.php?q=">#</a>', $txt);

(?<!\S) 表示 hashtag 之前的字符必须是空白字符(不是非空白字符 (\S))。 <br /> 中的 > 不符合该要求。您可能可以断言主题标签之前的字符不是 word 字符 ([A-Za-z0-9_]):

$txt = preg_replace('/(?<!\w)#([0-9a-zA-Z]+)/m', '<a href="index.php?q=">#</a>', $txt);

Demo on 3v4l.org