In PHP I have a String $string and an array $acronyms (in the form "UK" => "United Kingdom").
Now I want to replace all acronyms within $string by some HTML Tags. For example Hello UK
should turn into Hello <acronym title="United Kingdom">UK</acronym></pre>
I do it this way:
foreach($acronyms as $acronym => $tooltip){
$string = preg_replace('/'.$acronym.'/i', ''.$acronym.'', $string);
}
The problem is: Let's say I have a text Hello UK
and have an array to replace "UK" with "United Kingdom" and "Kingdom" with "RandomWord". Then the text will replace into Hello <acronym title="United <acronym title="RandomWord">Kingdom</acronym>">UK</acronym>
which obviously is chaos.
So the question is: How do I make my preg_replace only look for the words while they are NOT within an <acronym>
tag? (neither in title-attribute, nor within the tag itself)
Edit: second attempt according to a response (because I can't put code in reply). Still the same problem, the text within acronym gets replaced a second time...
foreach($acronyms as $acronym => $tooltip){
$acronyms[$acronym] = '<acronym title="'.$tooltip.'">'.$acronym.'</acronym>';
}
$string = str_ireplace(array_keys($acronyms), array_values($acronyms), $string);