Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to replace words with preg_replace without duplicates?
    primarykey
    data
    text
    <p>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.</p> <p>Example:</p> <pre> Welpen /hunde Chihuahua Welpen /hunde,chihuahua </pre> <pre><code>function seo_internal_links($str, $links, $limit) { foreach($links AS $link){ $pattern[$k] = "~\b($link[phrase])\b~i"; $replace[$k] = '&lt;a href="'.$link[link].'"&gt;\\1&lt;/a&gt;'; $k++; } return preg_replace($pattern,$replace,$str, $limit); } seo_internal_links($ad[text], $seo_internal_links, $limit = 1); </code></pre> <p>This will result in:</p> <pre><code>&lt;a href="//hunde,chihuahua"&gt;Chihuahua &lt;a href="/hunde"&gt;Welpen&lt;/a&gt;&lt;/a&gt; </code></pre> <p>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.</p> <hr> <p>Some adtional explanation.</p> <p>I am pulling the words to replace and their coresponding replacements out of a table. There are hundreds of them. </p> <pre><code> $stmt =" SELECT * FROM $T73 ORDER BY prio desc "; $result = execute_stmt($stmt, $link); while ($row = mysql_fetch_object($result)){ $seo_internal_links[$row-&gt;ID]['phrase'] = $row-&gt;phrase; $seo_internal_links[$row-&gt;ID]['link'] = $row-&gt;link; } $my[text] = seo_internal_links($my[text], $seo_internal_links, $limit = 1); </code></pre> <p>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.</p> <p>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 "<a href="/bla">beagle welpen</a>. If the word "welpen" is also inside the table, it will break the html code and insert a href tag again.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload