Reputation: 2463
How can you check if text typed in from a user is an url?
Lets say I want to check if the text is a url and then check if the string has "youtube.com" in it. Afterwards, I want to get the portion of the link which is of interest for me between the substrings "watch?v=" and any "&" parameters if they do exist.
Upvotes: 2
Views: 372
Reputation: 94147
parse_url() is probably a good choice here. If you get a bad URL, the function will return false
. Otherwise, it will break the URL up into its component pieces and you can use the ones you need.
Example:
$urlParts = parse_url('http://www.youtube.com/watch?v=MX0D4oZwCsA');
if ($urlParts == false) echo "Bad URL";
else echo "Param string is ".$urlParts['query'];
Outputs:
Param string is v=MX0D4oZwCsA
You could split the query portion as needed using explode() for specific parameters.
Edit: Keep in mind that parse_url()
tries as hard as possible to parse the string it is given, so bad URLs will often succeed, although the resulting data array will be very odd. It's obviously up to you how definitive you want your validation to be and what exactly you require out of your user input.
Upvotes: 5
Reputation: 5127
Its strongly recommended not to use parse_url() for url validation. here is a nice solution.
Upvotes: 0
Reputation: 3821
preg_match('#watch\?v=([^&]+)#', $url, $matches);
echo $matches[1];
Upvotes: 0