Question

i'm working on a website that includes a glossary, in which a few words are explained. Additionaly I want to describe the terms in an article by putting them in spans with a title attribute.

I get all the terms from the database in an array:

$terms = array(
    'word1' => 'This is a short description of word1',
    'word2' => 'word2 maybe has something to do with word1'
);

The String containing the text could be:

$string = 'In this sentence I want to explain both, word1 and word2.';

I tried to simply replace the words contained in the string by a simple str_ireplace():

foreach($terms as $term => $description)
{
    $string = str_ireplace($term, '<span class="help" title="' . $description . '">' . $term . '</span>', $string);
}

What happens now is, that word1 and word2 is replaced correctly. But by iterating a second time over the text to search and replace word2, it finds word1 again - in the title of the already created span.

So the result for word1 would look like this:

<span class="help" title="This is a short description of <span class="help" title="This is a short description of word1">word1</span>word1</span>

How could I prevent PHP from replacing the same word in the title tag of an existing span? I wouldn't like to use preg_replace() for that, to not parse html to it.

How could I do that?

Lovely Greets from germany Chris

Was it helpful?

Solution

You can use strtr for that:

$string = 'In this sentence I want to explain both, word1 and word2.';
$terms = array(
    'word1' => '<span title="This is a short description of word1">word1</span>',
    'word2' => '<span title="word2 maybe has something to do with word1">word1</span>',
);
echo strtr($string, $terms);

In this sentence I want to explain both, <span title="This is a short description of word1">word1</span> and <span title="word2 maybe has something to do with word1">word1</span>.

See http://codepad.org/VEBLQcBe for a working example

strtr will translate characters or replace substrings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top