a1amattyj Posted January 26, 2011 Share Posted January 26, 2011 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 Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted January 26, 2011 Share Posted January 26, 2011 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 />"; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.