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.

LVL 14
ziffgoneAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RoonaanCommented:
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-
ziffgoneAuthor Commented:
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.
RoonaanCommented:
Try using this one:

$preg = '#(http://[^/]+(/|/[\w\.]+)?)#i';

-r-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

ziffgoneAuthor Commented:
Unfortunately, that matches the url, PLUS everything that comes after the url.

Thanks.
ziffgoneAuthor Commented:
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...
RoonaanCommented:
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-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.