Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains nothing but an URL in PHP

I am wondering if this is a proper way to check, if a string contains nothing but an URL:

if (stripos($string, 'http') == 0 && !preg_match('/\s/',$string)) {   do_something(); } 

stripos() checks if the string starts with "http"
preg_match() checks if the string contains spaces

If not so, I assume that the string is nothing but an URL - but is that assumption valid? Are there better ways to achieve this?

like image 477
yan Avatar asked Feb 21 '13 20:02

yan


People also ask

How check string is URL or not in PHP?

This question already has answers here: $text = "something.com"; //this is a url if (! IsUrl($text)){ echo "No it is not url"; exit; // die well }else{ echo "Yes it is url"; // my else codes goes } function IsUrl($url){ // ??? }

How do I check if a string contains a string in PHP?

Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .


1 Answers

Use filter_var()

if (filter_var($string, FILTER_VALIDATE_URL)) {    // you're good } 

The filters can be even more refined. See the manual for more on this.

like image 173
John Conde Avatar answered Oct 12 '22 15:10

John Conde