Skip to content

Instantly share code, notes, and snippets.

@ibrahimtuzlak0295
Last active November 8, 2019 19:49
Show Gist options
  • Save ibrahimtuzlak0295/cf0a4bca7f3cba2961ac3fc7e1586e4c to your computer and use it in GitHub Desktop.
Save ibrahimtuzlak0295/cf0a4bca7f3cba2961ac3fc7e1586e4c to your computer and use it in GitHub Desktop.
Filter a value in a way that it always must be prepended with either http:// or https://.
/**
 * 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment