Solved: Regular expression for url

All your question about php
Post Reply
mister_v
Posts: 188
Joined: Thu Mar 04, 2010 9:19 pm

Solved: Regular expression for url

Post by mister_v »

Hi,

I would like to match all url's find in a text.
with preg_replace().

Can anyone give me the perfect pattern to math them?

Thanks
Last edited by mister_v on Mon Nov 12, 2012 8:26 pm, edited 1 time in total.
chris
Site Admin
Posts: 194
Joined: Mon Jul 21, 2008 9:52 am

Re: Regular expression for url

Post by chris »

I find the following pattern works well for me
"@((https?://|ftp://)([-\w\.]+)+(:\d+)?(/([\w/_\.\-\+\~\=\:]*(\?\S+)?)?)?)@"

Code: Select all

$pattern=array("@((https?://|ftp://)([-\w\.]+)+(:\d+)?(/([\w/_\.\-\+\~\=\:]*(\?\S+)?)?)?)@");
$replace=array("[Somtehing]\\1");
$str=preg_replace($pattern,$replace,$string);
chris
Site Admin
Posts: 194
Joined: Mon Jul 21, 2008 9:52 am

Re: Regular expression for url

Post by chris »

On this site you get a good overview of several patterns,
with there pro's and con's:
http://mathiasbynens.be/demo/url-regex
mister_v
Posts: 188
Joined: Thu Mar 04, 2010 9:19 pm

Re: Solved: Regular expression for url

Post by mister_v »

Thanks, this helps me a lot.
Post Reply