Hi I wrote a short script that simply replace text with links. But then I had a big problem- If the text was already in a link then you can imagine what will happen- it will something like that- <a><a>text</a></a> I have been told that regular expression is the best way to go. how can I use ereg_replace in order to replace text with link but only if the text is not already in a link in other words replace text with link only if it’s not surrounded with ‘’<a†and “/a>†thanks
Lets say the variable for the text is $var Just make an if statment that checks to see if this code returns a value >= 1 echo substr_count($var, '<a'); If it does then don't change the text, if it doesnt then do... I think that should work anyhow =P
There are two options: 1. Don't touch a text containing anchor tags: ... if (stristr($text,'<a') === FALSE) { $link= ............ // use your favorite way to convert text to links } Code (markup): (this assumes all existing anchor tags in $text are valid) 2. Remove all anchor tags from the text before creating a link $text=preg_replace('/\<[\/]{0,1}a.*\>/iU', '', $text); $link= ............ ; // use your favorite way to convert text to links Code (markup):
Try this: <?php $textToReplace = "text"; $String = "Here is some sample text, the word <a>text</a> in a tags should be left alone"; $NewString = preg_replace( "/[^>]($textToReplace)[^<]/i", ' <a href="link.htm">$1</a>', $String ); echo $NewString; ?> PHP: Brew
Thanks to you all. Brewster was the closest one to the solution (remember that I'm talking about a whole page not a single line) Brewster's script was OK but- 1. What if there are space between the text and the tag (<a> text </a>) So,' <a> text </a>' will become ' <a> <a href="link.htm">text</a> </a>' 2.what if 'text' is in a different tag like '<b>text<b/>'. I would like it to be replced to So it will become '<b><a href="link.htm">text</a><b/>' I need a script that covers those cases two. thanks