Need to match text URL

Hello Experts,

I need to match a URL - "" etc - in a text file using preg_match. All I need is the Regex to do this. Thanks.

LVL 14
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.

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>';

ziffgoneAuthor Commented:

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

or only


Try using this one:

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


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.

ziffgoneAuthor Commented:

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.

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 :-)

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

From novice to tech pro — start learning today.