PHP在字符串中以任何形式查找URL
I'm looking for some form of input security on a project I working on. Basically I wish to flag text if the user has inputted any form of a URL.
IE 'For more of my pic visit myhotpic.net'
Hence it would detect a url and then I can flag the string for validation via staff. So I would need to check for any form of a URL.
There is a similar question here Finding urls from text string via php and regex? with an answer. But I have tired this with various strings and I do not get the expected results.
For example
$pattern = '#(www\.|https?:\/\/){?}[a-zA-Z0-9]{2,254}\.[a-zA-Z0-9]{2,4}(\S*)#i';
$count = preg_match_all($pattern, 'http://www.Imaurl.com', $matches, PREG_PATTERN_ORDER);
returns matches as
array(3) {
[0]=>
array(0) {
}
[1]=>
array(0) {
}
[2]=>
array(0) {
}
}
and no error is return via preg_last_error()
Why is this not working? Is there an error in the Regex? I would assume it to be fine as other users have had success with it.
I cannot seem to find a suitable answer for my problem anywhere else.
In the regex, change {?}
to just ?
. Then it will work. No idea what {?}
is supposed to mean (I've never seen anything like that).
Your regex will work fine for some URLs, but you should be aware that URLs can be much more complicated than you might assume, and a regex that can match every URL is VERY complex. You might want to look up a better regex—you only need one complicated enough to handle the sorts of URLs you're expecting to match.