【问题标题】:preg_replace to exclude <a href='''></a> PHPpreg_replace 排除 <a href='''></a> PHP
【发布时间】:2019-04-23 01:58:32
【问题描述】:

我正在使用 preg_replace 将文本中的关键字替换为 href 标签,我的正则表达式运行良好,现在我的代码是:

$newstring2 = preg_replace("/\p{L}*?".preg_quote($match[$i])."\p{L}*/ui", "<a href='".$url."' class='link'>$0</a>", $newstring);

唯一的问题是,我需要排除 &lt;a href='https://keyword.cz' title="keyword"&gt;keyword&lt;/a&gt; 中的任何关键字

这是我找到的https://stackoverflow.com/a/22821650/4928816

那么有人可以帮我将这两个正则表达式合并在一起吗?

例子:

$text = 'this is sample text about something what is text.'
$keyword = 'text'

现在感谢我的正则表达式:

$text= 'this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>.'

但如果文本是:

$text= 'this is sample <a href='text.php'>text</a> about something what is <a href='somelink.php'>text</a>.'

这就是我得到的例子:

$text= 'this is sample <a href='<a href='somelink.php'>text.php</a>'><a href='somelink.php'>text</a></a> about something what is <a href='somelink.php'><a href='somelink.php'>text</a></a>.'

更新: 为什么我需要这个。 正在开发功能以在充满标签的特定博客文章中用特定 URL 替换所有关键字。 例如如果

$keyword = 'key';

我需要用 href 标记查找并替换整个世界,例如: Key、Keyword、keyword、keylock、mykey、keys 或 Key、Keyword 支持 UNICODE

【问题讨论】:

标签: php regex replace preg-replace


【解决方案1】:

如果必须使用正则表达式,我认为 PCRE 动词是您的最佳选择。排除所有链接,然后搜索带有单词边界的术语。

<a[\S\s]+?<\/a>(*SKIP)(*FAIL)|\bTERM\b

演示:https://regex101.com/r/KlE1kc/1/

这个缺陷的一个例子是a 曾经有一个&lt;/a&gt;。例如onclick='write("&lt;/a&gt;")' 解析器确实是最好的方法。 HTML 和正则表达式有很多陷阱。

【讨论】:

    【解决方案2】:

    如何使用负前瞻。 Regex

    说明:捕获所有被称为text 的关键字并用它替换一些链接,但不要捕获那些后面有&lt;/a&gt; 的关键字。

    $re = '/(text)(?!<\/a>)/m';
    $str = 'this is sample text about something what is text.
    
    this is sample <a href=\'somelink.php\'>text</a> about something what is <a href=\'somelink.php\'>text</a>.';
    $subst = '<a href=\'somelink.php\'>$1</a>';
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    输出:

    this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>. 
    
    this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>.
    

    演示: https://3v4l.org/DVTB1

    【讨论】:

    • 这具有相同的效果,但如果属性具有值 regex101.com/r/oRVBvi/2
    • 这可能可行,但此 preg_replace 必须排除 href 并匹配任何 FULL 关键字,没有区别。关键字关键字、关键字 mykeyword 之间。那么您认为您发布的内容可以在我上面给出的正则表达式中使用吗?我需要这样的东西: $newstring1 = preg_replace("/\p{L}*?/(text)(?!)\p{L}*/ui", "$0", $newstring);
    猜你喜欢
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多