Jump to content

STR Replace


a1amattyj

Recommended Posts

Hello,

 

I'm trying to convert a paragraph of text which is already html formatted.

 

I wish to find keywords, such as, 'PHP', which are contained in the paragraph, and replace them with a link, for example <a href="http:/www...">PHP</a>

 

str_replace('PHP', '<A href=""....">PHP</a>', $content);

 

 

My problem arises when some of these keywords are already contained in a link, so say, visit PHP website, is all one link, so str_replace would simply convert the PHP in this string, to two links for one single word.

 

<a href="">visit <A href=""....">PHP</a> website</a>

How could this problem be resolved?

 

Thanks

 

Link to comment
Share on other sites

you'll probably need something fancier like preg_replace. an example, replacing php if not already in a link:

 

$string1 = "hello world php is great.";
$string2 = "hellow world <a href='http://www.cnn.com'>php</a> is great.";

$replace_link = "<a href='http://www.yahoo.com'>php</a>";
$pattern = '/([^>])php([^<])/';

$string1 = preg_replace($pattern, '$1'.$replace_link.'$2', $string1);
$string2 = preg_replace($pattern, '$1'.$replace_link.'$2', $string2);

echo "string1: $string1 <br />";
echo "string2: $string2 <br />";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.