$re = '/^((http|https|ftp|ftps):\/\/)?(?<url_host>(\[[^\]]+\]|[^\/:\n]+))(?<url_port>(:\d+)?)(\/)?/m';
$str = 'sony.com
http://cnn.com/story
https://google.com:444/stuff
1.2.3.4:12/ok
1.2.3.4/ok
2.2.2.2:443
/dontmatchme
ftp://mononym/path
http://google.com
www.test
http://[2001:1890:1c00:6500::d:7]/rar/
[2001:1890:1c00:6500::d:7]
[2001:1890:1c00:6500::d:7]/test
http://[2001:1890:1c00:6500::d:7]:8080/rar/
[2001:1890:1c00:6500::d:7]:8080
[2001:1890:1c00:6500::d:7]:4/test
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php