dongma7725 2011-05-15 22:20
浏览 48
已采纳

正则表达式上缺少奇怪的空白

I have this kind of regex on PHP :

$str="first word https://www.helloz.it last word";
$str=preg_replace(
    '#[^"](((http|https|ftp)://)[^\s
]+)#',
    '<a class="lforum" href="$1">$1</a>',
    $str);
echo nl2br($str);

And the output that I'll expect is :

first word <a class="lforum" href="https://www.helloz.it">https://www.helloz.it</a> last word

but in fact the output is :

first word<a class="lforum" href="https://www.helloz.it">https://www.helloz.it</a> last word

(notice the missing whitespace between first word and <a class...

Where is it vanished that whitespace? :) Thanks

  • 写回答

2条回答 默认 最新

  • duanli9591 2011-05-15 22:26
    关注

    [^"] says "match a character that isn't "". A space character is matched by this, so it is replaced by your regex.

    Use a negative lookbehind instead:

    '#(?<!")(((http|https|ftp)://)[^\s
    ]+)#',
    

    This says "match the string if it doesn't follow a quotation mark". Preceding characters are not therefore included in your matched content.

    See regular-expressions.info for information about lookbehinds.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改