[英]Using regex in preg_replace to match an html href anchor tag
[英]Can Regex/preg_replace be used to add an anchor tag to a keyword?
我希望能夠切換這個......
My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this keyword here.
至...
My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this [a href="url"]keyword[/a] here.
我不能簡單地替換“關鍵字”的所有實例,因為有些是在現有的錨標記中使用。
注意:在Linux上使用PHP5 preg_replace。
單獨使用正則表達式不能這樣做。 正則表達式是無上下文的 - 它們只是匹配模式,而不考慮周圍環境。 要執行您想要的操作,您需要將源解析為抽象表示,然后將其轉換為目標輸出。
使用正則表達式可能不是解決此問題的最佳方法,但這是一個快速解決方案:
function link_keywords($str, $keyword, $url) {
$keyword = preg_quote($keyword, '/');
$url = htmlspecialchars($url);
// Use split the string on all <a> tags, keeping the matched delimiters:
$split_str = preg_split('#(<a\s.*?</a>)#i', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
// loop through the results and process the sections between <a> tags
$result = '';
foreach ($split_str as $sub_str) {
if (preg_match('#^<a\s.*?</a>$#i', $sub_str)) {
$result .= $sub_str;
} else {
// split on all remaining tags
$split_sub_str = preg_split('/(<.+?>)/', $sub_str, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($split_sub_str as $sub_sub_str) {
if (preg_match('/^<.+>$/', $sub_sub_str)) {
$result .= $sub_sub_str;
} else {
$result .= preg_replace('/'.$keyword.'/', '<a href="'.$url.'">$0</a>', $sub_sub_str);
}
}
}
}
return $result;
}
一般的想法是將字符串拆分為鏈接和其他所有內容。 然后將鏈接標記之外的所有內容拆分為標記和純文本,並將鏈接插入到純文本中。 這將阻止[p class =“keyword”]擴展為[p class =“[a href =”url“] keyword [/ a]”]。
同樣,我會嘗試找到一個不涉及正則表達式的簡單解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.