Wordpress - How to check if a string is a valid URL

Use the native php function Filter Validator

if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
    die('Not a valid URL');
}

I know this is an old post, but for anyone visiting it's also worth considering the WP functions esc_url() and esc_url_raw(), the latter being safe for databases entries etc, as it does not encode entities. esc_url() does encode entities and so is good for display to users.

In the source you can see that esc_url() checks for a whitelist of allowed protocols and structure and so avoids some of the vulnerabilities of FILTER_VALIDATE_URL noted by the link posed by @tobltobs.


I found wp_http_validate_url quite convenient to check if a string in valid URL or not while working on my project.

Take a reference from here: https://developer.wordpress.org/reference/functions/wp_http_validate_url/

For example:

$val = 'http://somevalidurl.com';
if ( wp_http_validate_url( $val ) ) {

    // It's valid URL;

} else {

    // It's NOT valid URL;

}

It returns the URL itself if it's valid,else false.

Tags:

Php

Validation