[英]preg_replace to exclude <a href='''></a> PHP
我正在使用preg_replace來替換帶有href標簽的文本中的關鍵字,我的正則表達式工作非常好,現在我的代碼是:
$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>
內的<a href='https://keyword.cz' title="keyword">keyword</a>
這是我發現的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,關鍵字,keylock,mykey,key或KeY, Unicode支持的關鍵字
負面的前瞻性如何? 正則表達式
說明 :捕獲所有被稱為text
的關鍵字,並用一些鏈接替換它,但是不捕獲在其后帶有</a>
那些關鍵字。
$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
如果必須使用正則表達式來完成,我認為PCRE動詞是您的最佳選擇。 排除所有鏈接,然后搜索帶有單詞邊界的術語。
<a[\S\s]+?<\/a>(*SKIP)(*FAIL)|\bTERM\b
演示: https : //regex101.com/r/KlE1kc/1/
對此有缺陷的一個例子是,如果a
中有一個</a>
。 例如onclick='write("</a>")'
解析器確實是最好的方法。 HTML和正則表達式有很多陷阱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.