【问题标题】:PHP Preg Replace doesn't work AFTER line breakPHP Preg Replace 在换行后不起作用
【发布时间】:2019-11-06 00:57:39
【问题描述】:

拥有获取 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=$1">#$1</a>', $txt);

【问题讨论】:

  • 为我工作3v4l.org/RPVEW
  • @Nick 尝试使用换行符替换,但失败了。让我认为它是
    导致的问题。但我不知道解决这个问题的正则表达式3v4l.org/OMMPh

标签: php preg-replace str-replace


【解决方案1】:

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

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

Demo on 3v4l.org

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2011-01-26
    • 2010-12-02
    相关资源
    最近更新 更多