我正在html頁面上創建一個preg_replace。我的模式旨在為html中的某些單詞添加周圍標記。但是,有時我的正則表達式會修改html標記。例如,當我嘗試替換此文本時:<a href="example.com" alt="yasar home page">yasar</a>這樣yasar讀取<span class="selected-word">yasar</span>,我的正則表達式也替換了錨標記的alt屬性中的yasar。preg_replace()我正在使用的電流看起來像這樣:preg_replace("/(asf|gfd|oyws)/", '<span class=something>${1}</span>',$target);如何制作正則表達式,使其與html標簽內的任何內容都不匹配?
3 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
Yasar,恢復了這個問題,因為它有另一個未提及的解決方案。
此解決方案不會僅檢查下一個標記字符是否為開始標記,而是跳過所有標記<full tags>。
有關使用正則表達式解析html的所有免責聲明,這里是正則表達式:
<[^>]*>(*SKIP)(*F)|word1|word2|word3
這是一個演示。在代碼中,它看起來像這樣:
$target = "word1 <a skip this word2 >word2 again</a> word3";
$regex = "~<[^>]*>(*SKIP)(*F)|word1|word2|word3~";
$repl= '<span class="">\0</span>';
$new=preg_replace($regex,$repl,$target);
echo htmlentities($new);
- 3 回答
- 0 關注
- 1042 瀏覽
添加回答
舉報
0/150
提交
取消