Re: preg_replace help
| From: | Gaylen Fraley | Date: | Sun, 13 Jan 2002 04:48:49 +0000 |
| Subject: | Re: preg_replace help | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-80333@lists.php.net to get a copy of this message | ||
First of all, thanks to everyone who replied! I have several good
suggestions. Here is one that seems to work pretty well, to cover a
multitude of situations:
$msg =
eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])","<a
href=\"\\1://\\2\\3\" target=\"_blank\">\\1://\\2\\3</a>", $msg);
The only problem is that if a correctly formatted link is already in the
text, then this routine tries to add an additional href and it gets all
messed up. Is there any way that I can use this algorithm and logically
tell it not to do the replace if the anchor tags are already in place? I
can't just search for an anchor <a> tag because there can be several in the
text.
Example:
$myLink = "<a href=\"http://www.mytest.com\"
target=\"_n\">Testing</a>";
echo makeLink($myLink);
Creates $msg =
<a href="<a href="http://www.mytest.com"
target="_blank">http://www.mytest.com</a>"
target="_n">Testing</a>
Any suggestions?
"Gaylen Fraley" <gfraley5@earthlink.net> wrote in message
news:20020112032023.17734.qmail@pb1.pair.com...
> I have need to be able to replace text within a string to turn it into a
> link. In other words, I might have a phrase lik:
>
> "blah, blah, blah, please visit my site at www.mysite.com. blah,
> blah,blah".
>
> I need to have the string converted to "blah, blah, blah, please visit my
> site at http://www.mysite.com. blah, blah,blah". The
> link might have
more
> than 3 sections and won't necessarily end in .com (.net,.com.nl, etc.).
>
> Here is what I have been testing (then I get stuck):
> $myLink = "Please visit my web site at www.mysite.com. You will be glad
you
> did!";
> $repLink = preg_replace("/(www.)/i","<a
> href=http://\\1",$myLink);
>
> which yields
> Please visit my web site at <a href=http://www.mysite.com.
> You will be
glad
> you did!
>
> What I would need is
> Please visit my web site at <a
> href=http://www.mysite.com>www.mysite.com</a>. You
> will be glad you did!
>
> To be truthful, pattern matching is giving me migraines! Programming has
> always been natural to me (32 years of it), but this challenge (eregi,
> preg_match,etc.) is making me crazy! Can someone recommend a good
tutorial
> or book on this subject?
>
> Thanks!
>
>
>