How to Check String is URL or Not in PHP?

03-Apr-2023

.

Admin

How to Check String is URL or Not in PHP?

Hi Dev,

This example is focused on How to check if is url or not PHP. step by step explain string contains check if a specific text using PHP . I explained simply step by step check if a string is URL or not PHP with code examples. This post will give you simple example of Validate string URL with PHP example. So, let's follow few step to create example of check if URL contains a string PHP.

Example 1:


index.php

<?php

$url = "https://www.nicesnippets.com";

// Validate url

if (filter_var($url, FILTER_VALIDATE_URL)) {

echo("$url is a valid URL");

} else {

echo("$url is not a valid URL");

}

?>

Output:

https://www.nicesnippets.com is a valid URL

Example 2:

index.php

<?php

$url = "https://www.nicesnippets.com/nices/index";

// Search substring

$key = 'nices';

if (strpos($url, $key) == false) {

echo $key . ' not exists in the URL <br>';

}

else {

echo $key . ' exists in the URL <br>';

}

// Another search substring

$key = 'function';

if (strpos($url, $key) == false) {

echo $key . ' not exists in the URL';

}

else {

echo $key . ' exists in the URL';

}

?>

Output:

nices exists in the URL

function not exists in the URL

I hope it could help you...

#PHP