trim is the fastest way to remove first and last char.
Benchmark comparsion 4 different ways to trim string with '/'
4 functions with the same result - array exploded by '/'
<?php
$s = '/catalog/lyustry/svet/dom-i-svet/';
$times = 100000;
print cycle("str_preg('$s');", $times);
print cycle("str_preg2('$s');", $times);
print cycle("str_sub_replace('$s');", $times);
print cycle("str_trim('$s');", $times);
print cycle("str_clear('$s');", $times);
function cycle($function, $times){
$count = 0;
if($times < 1){
return false;
}
$start = microtime(true);
while($times > $count){
eval($function);
$count++;
}
$end = microtime(true) - $start;
return "\n $function exec time: $end";
}
function str_clear($s){
$s = explode('/', $s);
$s = array_filter($s, function ($s){if(!empty($s)) return true;});
return $s;
}
function str_preg2($s){
$s = preg_replace('/((?<!.)\/(?=.))?((?<=.)\/(?!.))?/i', '', $s);
$s = explode('/', $s);
return $s;
}
function str_preg($s){
$s = preg_replace('/^(\/?)(.*?)(\/?)$/i', '$2', $s);
$s = explode('/', $s);
return $s;
}
function str_sub_replace($s){
$s = str_replace('/' , '' , mb_substr( $s , 0, 1)) . mb_substr( $s , 1, -1) . str_replace('/', '', mb_substr( $s , -1));
$s = explode('/', $s);
return $s;
}
function str_trim($s){
$s = trim($s, '/');
$s = explode('/', $s);
return $s;
}