1

Hi can someone help me identify if a url is present in a string using PHP?

I want to pull in a full string i.e. "Hi please visit http://domain.com/12345 today" and strip out the full url not just the domain name.

Thanks

  • Take a look at this article from Jeff Atwood's blog "Coding Horror": [The Problem With URLs](http://www.codinghorror.com/blog/archives/001181.html) – VVS Jun 04 '09 at 15:33

2 Answers2

2

You probably want something like this:

RegEx Guru: Detecting URLs in Text

Read up on this and understand the trade-offs of each approach. For me, \bhttp://\S+ is totally acceptable, because I'm not interested in catering to those who would put links with spaces (or surround their links with parens) into plain text... (but I'm not very accomodating I guess)

cgp
  • 41,026
  • 12
  • 101
  • 131
1

here's an example

$str = file_get_contents('http://www.sitepoint.com');

preg_match_all('~(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)~', $str, $matches);

print_r($matches);
Galen
  • 29,976
  • 9
  • 71
  • 89