- is_numeric: documentation ( source)
- microtime: documentation ( source)
- preg_match: documentation ( source)
- explode: documentation ( source)
<?php
// String manipulation (explode and manual comparison)
$sstart = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$uri = 'user/123';
$segments = explode('/', $uri);
if ($segments[0] === 'user' && is_numeric($segments[1])) {
$id = $segments[1];
}
}
$string = (microtime(true) - $sstart);
echo 'String manipulation: ' . $string . ' seconds'.PHP_EOL;
// Regex equivalent
$rstart = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$uri = 'user/123';
if (preg_match('#^user/(\d+)$#', $uri, $matches)) {
$id = $matches[1];
}
}
$regex = (microtime(true) - $rstart);
echo 'Regex: ' . $regex . ' seconds'.PHP_EOL;
echo 'Diff: '.((($regex - $string) / $string) * 100).'%';