I want to create a PHP function which will replace certain words out of a text with internal links. That works so far, but if I have two matches, I end up with invalid HTML code.
Example:
Welpen /hunde Chihuahua Welpen /hunde,chihuahua
function seo_inte开发者_如何转开发rnal_links($str, $links, $limit) {
foreach($links AS $link){
$pattern[$k] = "~\b($link[phrase])\b~i";
$replace[$k] = '<a href="'.$link[link].'">\\1</a>';
$k++;
}
return preg_replace($pattern,$replace,$str, $limit);
}
seo_internal_links($ad[text], $seo_internal_links, $limit = 1);
This will result in:
<a href="//hunde,chihuahua">Chihuahua <a href="/hunde">Welpen</a></a>
Has somebody an idea on how to avoid this? I would also like to limit the amount of hits, but the limit in preg_replace accounts only for unique words, not the whole array.
Some adtional explanation.
I am pulling the words to replace and their coresponding replacements out of a table. There are hundreds of them.
$stmt ="
SELECT *
FROM $T73
ORDER BY prio desc
";
$result = execute_stmt($stmt, $link);
while ($row = mysql_fetch_object($result)){
$seo_internal_links[$row->ID]['phrase'] = $row->phrase;
$seo_internal_links[$row->ID]['link'] = $row->link;
}
$my[text] = seo_internal_links($my[text], $seo_internal_links, $limit = 1);
The Problem occures, because the replacement function will start at the beginning of the text again to search for the next word. Instead it should just continue inside the text.
My goal is to insert internal links to my website text whenever a relevant word is found inside a table full of keywords. For example replace "beagle welpen" with "beagle welpen. If the word "welpen" is also inside the table, it will break the html code and insert a href tag again.
Instead of using a loop, construct a single regular expression and modify your entire document in a single pass. That is, instead of these regular expressions:
~\b(foo)\b~i
~\b(bar)\b~i
~\b(baz)\b~i
Use just this one:
~\b(foo|bar|baz)\b~i
You might want to look at using implode
to contruct the regular expression.
You also need to be careful of characters that have a special meaning inside a regular expression. You may find preg_quote
useful for this.
精彩评论