/**
* Filter a value in a way that it always must be prepended with either http:// or https://.
* Useful when we must be sure a string will be treated as a URL.
* @param string $string Value to filter
* @return string Value prefixed with http:// or https://
*/
function httpize_string(string $string) : string
{
return preg_match('{https?://}', $string) ? $string : 'http://' . $string;
}
Examples:
$url_no_http = 'example.com';
$url_http = 'http://example.com';
$url_https = 'https://example.com';
echo httpize_string($url_no_http); // http://example.com
echo httpize_string($url_http); // http://example.com
echo httpize_string($url_https); // https://example.com