2

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 for not directing to regex based solution where a specific function exists.
@Sarwar Erfan — and what is wrong with regex based solutions? )
@SaltLake Harder to maintain, harder to comprehend, harder to debug. I'm sure I can add more to the list...
@SaltLake - Nothing is wrong with a Regexp solution, when there isn't already a nice, tried and tested, out of the box solution wrapped up in a convenient API.
SaltLake: Nothing wrong with regex actually :) The php function I think most probably uses regex under the hood. But, php must have used a tested pattern. Again, nothing against regex.
0
preg_match('#watch\?v=([^&]+)#', $url, $matches);
echo $matches[1];

Comments

0

Its strongly recommended not to use parse_url() for url validation. here is a nice solution.

2 Comments

Why not? That site does not explain the why.
You should also provide an explanation along with your link. StackOverflow should stand on it's own, and be enhanced by links, not replaced by them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.