Link to home
Start Free TrialLog in
Avatar of ziffgone
ziffgoneFlag for Canada

asked on

Need to match text URL

Hello Experts,

I need to match a URL - "http://www.anything.com/anypage.htm" etc - in a text file using preg_match. All I need is the Regex to do this. Thanks.

Avatar of Roonaan
Roonaan
Flag of Netherlands image

Try this:

$preg = '#(http://[^/]+/[^\s]+)#i';

if(preg_match($preg, $contents, $matches)) {
  $urls = $matches[1];
} else {
  $urls = array();
}

echo '<pre>'.var_export($urls,true).'</pre>';

-r-
Avatar of ziffgone

ASKER

Thanks,

works great for any url with additional directories, but how can I make it optional to match either:

http://www.anything.com/anypage.htm

or only

http://www.anything.com

??

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Unfortunately, that matches the url, PLUS everything that comes after the url.

Thanks.
Whup...

Got it....

$preg = '#(http:\/\/+[\w]+[\w-]+\.[\w._\/-]+)#i';

I actually had the Regex in a Javascript somewhere but couldn't figure out how to implement it. However Roonaan, you showed me the way, through predefining the Regex in '# ~~ #i', so, even though I pretty much answered my own question, I'll give you the points for helping clear up how to use the regex.

Thanks for your help.

Regards...
In php it doesn't realy matter wether you use /../ or #..# or even !..! as long as the two delimiters are the same character. You could even use "..*.i" althought that gets quite unreadable :-)

-r-