<?php
$urls = [
'absolute' => 'https://stackoverflow.com/questions/20248666/in-this-case-which-is-better-in-matching-regular-expression-or-parse-url',
'relative' => '/questions/20248666/in-this-case-which-is-better-in-matching-regular-expression-or-parse-url',
'absolute-with-query' => 'https://stackoverflow.com/questions/20248666/in-this-case-which-is-better-in-matching-regular-expression-or-parse-url?r=https://3v4l.org',
'relative-with-query' => '/questions/20248666/in-this-case-which-is-better-in-matching-regular-expression-or-parse-url?r=https://3v4l.org',
];
$parseTester = function ($url) {
$urlComponents = parse_url($url, PHP_URL_SCHEME);
return strncmp($url, '//', 2) && empty($urlComponents);
};
$regexpTester = function ($url) {
return preg_match('@^((\w+):)?//@', $url);
};
$strposTester = function ($url) {
return strpos($url, 'https://') !== 0
|| strpos($url, 'http://') !== 0
|| strpos($url, '//') !== 0;
};
$strposAlternativeTester = function ($url) {
if (strncmp($url, '//', 2) === 0) {
return false;
}
$pos = strpos($url, '://');
if ($pos === false) {
return true;
}
$queryPos = strpos($url, '?');
return $queryPos === false || $pos < $queryPos;
};
$test = function ($testerName, $callback) use ($urls) {
foreach ($urls as $scenario => $url) {
$time = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$callback($url);
}
echo "$testerName-$scenario: ", number_format(microtime(true) - $time, 10), "\n";
}
echo "\n";
};
$test('parseTester', $parseTester);
$test('regexpTester', $regexpTester);
$test('strposTester', $strposTester);
$test('strposAlternativeTester', $strposAlternativeTester);
preferences:
17.11 ms | 410 KiB | 5 Q