【问题标题】:Replace all urls in string not matching url pattern in php替换字符串中与php中的url模式不匹配的所有url
【发布时间】:2014-03-05 21:17:11
【问题描述】:

我正在使用以下代码从 PHP 中的 HTML 文本块中过滤掉 url。

preg_replace('#<a(?![^>]+?href="?http://keepthisdomain.com/foo/bar"?).*?>(.*?)</a>#i', '\1', $text);

它旨在替换所有不匹配指定 url 模式的 url。但是我确实想包含所有设置了属性 rel="shadowbox[a]" 的标签。

如何修改这个 preg_replace 来做到这一点?

【问题讨论】:

  • 澄清一下,这是一个匹配:(1) a 标签与指定的 URL 模式 rel="shadowbox[a]" 属性,或 (2) a 标签使用指定的 URL 模式 rel="shadowbox[a]" 属性?
  • P.S.对于the reasons set forth in this answer,你最好不要使用正则表达式,而是使用解析器。
  • 这是一个带有 rel="shadowbox[a]" 属性的标签。我想保留这些网址(以及链接到keepthisdomain.com/foo/bar 的所有超链接)

标签: php regex preg-replace


【解决方案1】:

对于the reasons set forth in this answer,最好不要使用正则表达式,而是使用解析器。

也就是说,您可以使用正则表达式来做到这一点,但这很棘手:

preg_replace('#<a(?![^>]+?\bhref="?http://keepthisdomain\.com/foo/bar"?|[^>]+\brel="shadowbox\[a\]").*?>(.*?)</a>#i', '\1', $text);

正则表达式的详细信息:

<a(?![^>]+?\bhref="?http://keepthisdomain\.com/foo/bar"?|[^>]+\brel="shadowbox\[a\]").*?>(.*?)</a>

在以下四个标签中,只有第三个会被替换:

<a href="http://keepthisdomain.com/foo/bar">foo</a> // left alone
<a href="http://keepthisdomain.com/foo/bar" rel="shadowbox[a]">foo</a> // left alone
<a href="http://rejectthis.com/foo/bar">foo</a> // REPLACED
<a href="http://rejectthis.com/foo/bar" rel="shadowbox[a]">foo</a> // left alone

使用\.

进行了微调,使其与.com 中的文字. 匹配

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多