【问题标题】:preg_replace with URL problempreg_replace 与 URL 问题
【发布时间】:2011-03-28 19:38:37
【问题描述】:

我使用 preg_replace 在段落中自动插入 HTML 链接。

这是我目前使用的:

$pattern = "~(?!(?:[^<\[]+[>\]]|[^>\]]+<\/a>))(".preg_quote($find_keyword, '/').")\b~msUi";
$replacement = "<a href=\"http://$kw_url\" title=\"$find_keyword\">\$0</a>"; 
$article_content = preg_replace($pattern, $replacement, stripslashes($article_content), 1, $added );

效果很好,除了 1 个问题:

如果关键字是 URL,则不匹配和替换。

如果:$find_keyword="http://www.mysite.com/",即使在内容中,它也不会提供任何匹配项。

我已经尝试使用 preg_quote 转义 $find_keyword,但没有任何不同。

任何正则表达式专家知道解决方案吗?谢谢。

【问题讨论】:

  • 我已经尝试转义正斜杠,但没有任何不同。
  • 如果你通过 preg_quote() 传递 $find_keyword 会发生什么(你应该将所有输入都输入到正则表达式)?
  • 你有没有想过链接到http://example.com/"&lt;script&gt;alert("xss")&lt;/script&gt;的用户?
  • 我尝试时没有变化:$pattern = "~(?!(?:[^&lt;\[]+[&gt;\]]|[^&gt;\]]+&lt;\/a&gt;))(".preg_quote($find_keyword).")\b~msUi";
  • @user,所有 HTML 标签都从原始内容中剥离。

标签: php regex url replace preg-replace


【解决方案1】:

$find_keywords 中的正斜杠没有转义,这破坏了模式。

【讨论】:

  • 阅读 cmets。他们逃脱了,但没有任何区别。
【解决方案2】:

您可以通过

运行您的 find_keyword
$find_keyword=preg_quote("http://www.mysite.com/", '/');

http://www.php.net/manual/en/function.preg-quote.php

【讨论】:

  • 请发布示例 $article_content 输入和您想要的输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 2011-08-24
  • 1970-01-01
  • 2012-01-29
相关资源
最近更新 更多