preg_replace 排除 <a href='''></a>PHP [英] preg_replace to exclude <a href='''></a> PHP

查看:33
本文介绍了preg_replace 排除 <a href='''></a>PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 preg_replace 用 href 标签替换文本中的关键字,我的正则表达式工作得很棒,现在我的代码是:

Im using preg_replace to replace keywords in text with a href tag, my regex is working awesome, right now my code is:

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

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

Only problem with this is, that I need to exclude any keywords inside <a href='https://keyword.cz' title="keyword">keyword</a>

这是我发现的https://stackoverflow.com/a/22821650/4928816

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

So is here someone who can help me merge this two regex together?

示例:

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

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

Now thanks to my regex I get:

$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 替换所有关键字的功能.例如如果

Update: Why do I need this. Working on function to replace all keywords with specific URL in specific blog post full of tags.. For examle if

$keyword = 'key';

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

I need to find and replace full world with a href tag, for example: Key, Keyword, keyword, keylock, mykey, keys or also KeY, Keyword with UNICODE support

推荐答案

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

If it must be done with regex I think PCRE verbs are your best option. Exclude all links then search for the term with word boundaries.

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

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

这个缺陷的一个例子是 a 是否曾经有一个 .例如onclick='write("</a>")' 解析器确实是最好的方法.HTML 和正则表达式有很多问题.

an example of a flaw with this though is if the a ever had a </a> in it. e.g. onclick='write("</a>")' a parser is really the best approach. There are a lot of gotchas with HTML and regexs.

这篇关于preg_replace 排除 &lt;a href='''&gt;&lt;/a&gt;PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆