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.
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:
Outputs:
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.