Reputation: 46
I have a list of dictionary words which I load into an array. I grab a block of text from a database table text field.
I loop through the dictionary words, and on each iteration, I check the block of text for occurrences of the word. Whenever a match is found, I replace that word in the block with a hyperlinked version, so when the block of text is published I can hover over it with the mouse pointer and popup a definition.
This is simple to achieve with a regular expression:
$text = preg_replace("/($dictionary_word)/i", '<a href="" class="glossary_term">$1</a>', $text, -1, $count);
If I run the "dictionary word linker" more than once though, the links will be doubled up.
What I need to do is code regular expression that detects an open anchor tag that has not been closed by the time a dictionary word is reached. That way I will know that the word is already linked, so I skip over it.
I tried various combinations of look ahead and look behind, with no success.
Upvotes: 2
Views: 129
Reputation: 50220
To keep it simple, you can just check that the matched word is not immediately followed by </a>
:
"/\b($dictionary_word)\b(?!<\/a>)/i"
Note also the \b
addition. This will avoid matching the pit
in spitting
, for example (which would turn it into s<a ...>pit</a>ting
).
Perhaps you have other kinds of hyperlinked text in your documents? This will block all hyperlinked single words from being linked to the dictionary, which is appropriate since one word can't be part of two URLs. But none of this will detect words the middle of <a href="...">a longer stretch of linked text</a>
. If you need smarter behavior, you need more than a dumb regexp-replace approach.
Upvotes: 1
Reputation: 254
$str = "today is 2013-04-03, tomrrow is 2013-04-04";
$output1 = preg_replace("/(\d{4}-\d{2}-\d{2})/i", "happy day", $str, 1);
$output2 = preg_replace("/(\d{4}-\d{2}-\d{2})/i", "happy day", $str);
replace only for once.
echo $output1;
today is happy day, tomrrow is 2013-04-04
replace all
echo $output2;
today is happy day, tomrrow is happy day
did you see the difference ?
Upvotes: 0