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?
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){ // ??? }
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With