|
Posted by Mike P2 on 04/30/07 22:33
On Apr 30, 6:13 pm, Fabri <farsi.i.cazzi.pro...@mai.eh> wrote:
> I searched and tried to develop (with no luck) a function to do the
> following:
>
> I have a string that may be:
>
> "Le'ts go to <a href="my.htm">my car</a>. Tomorrow I'll have to buy a
> new car. My new car is <em>red</em>! Please don't think to be in Nascar!!"
>
> What I have to do is replace occurences of "car" with <a
> href="/...">car</a> BUT in these cases:
>
> - if there is already a wrapped link
> - if car is part of another word
Regular Expressions. preg_replace() is PERL compatible regular
expressions, that's just my preference. You can use the normal PHP
regex, too (ereg_replace()).
$string = preg_replace( '#([\s\(])my car([\s\)\.])#i', '$1<a
href="...">my car</a>$2', $string );
The character groups on either side of "my car" allow "my car" to be
next to new lines, spaces, tabs, parenthesis, and periods. You can
take away the character groups and $1 and $2 in the second argument to
let it be replaced in any context, even in the middle of some text
with no spaces. If you want to learn more on regular expressions,
there might be a newsgroup for that too, and of coarse your favorite
search engine will be a big help. There are entire books written on
regex.
preg_replace():
http://php.net/manual/en/function.preg-replace
[Back to original message]
|