Page 1 of 1

bold all text except links

Posted: Mon Jul 27, 2009 4:46 am
by richtalbot
Hello,

We have a bit of code that bolds a key term within a given block of text (eg. from a search result).

It's working fine, except sometimes, the text can contain a link.

Say $search_term is "dog", and $old_string is:

Code: Select all

A lot of dogs are happy to go for a walk. You may prefer our <a href="/dog-walking.html">Dog Walking Page</a>.
Currently, we are using:
$new_string = str_replace($search_term, "<b>".$search_term."</b>", $old_string);

But this, of course, makes the string this:

Code: Select all

A lot of <b>dog</b>s are happy to go for a walk. You may prefer our <a href="/<b>dog</b>-walking.html"><b>Dog</b> Walking Page</a>.
Note the 'dog' part in the URL is broken. Therefore when people click on the link, the link is broken as there is no such page as /<b>dog</b>-walking.html

How can we write the code so that the term is highlighted in bold, but NOT if the term is appearing in a link?

Thanks for your help.
Rich

Re: bold all text except links

Posted: Wed Jul 29, 2009 12:52 pm
by akuji36
I believe css can correct this text problem

bold when needed and kinks. In regard to broken link

try "escaping the dash".

Re: bold all text except links

Posted: Wed Jul 29, 2009 1:10 pm
by omniuni
Hm. I see your problem. I would try this:

1. Explode your string into an array
2. Test each element to see if it is or contains "<a"
3. If it does not, use your function to bold a word
4. If it does, stop processing the array elements with your function until ">" is found
5. Implode the array

Re: bold all text except links

Posted: Wed Jul 29, 2009 9:20 pm
by omniuni
McInfo, I think my suggestion was actually more efficient. That said, yours clearly wins in the awesomeness factor.

Re: bold all text except links

Posted: Wed Jul 29, 2009 11:22 pm
by omniuni
What if you simply used explode, instead? (by spaces)
Just use strstr() to see if it contains an opening bracket.

BTW, I'm impressed at your free time.

Re: bold all text except links

Posted: Thu Jul 30, 2009 4:15 am
by richtalbot
Hi Guys,

Thanks for your help - much appreciated. I used McInfo's first answer, as we are still running PHP4 at the moment, and couldn't use pass-by-reference in Foreach function.

It works well, and I have managed to modify the code, ueing Foreach for all search terms entered in the query.

I am impressed with the time you spent on this! I honestly wasn't really expecting a response. I am glad I joined phpdn and will come back next time I am stuck.

Regards, Rich