Home > Article > Backend Development > Summary of PHP collection speed research (original)_PHP tutorial
Note: All functions below do not use regular expressions.
The above are the three functions to extract the first match, achieving the same purpose
function str_cut($str,$start, $end) {//Extract the first match, efficiency The highest, split first and then replace
$content = strstr( $str, $start );
$content = substr( $content, strlen( $start ), strpos( $content, $end ) - strlen( $ start ) );
return $content;
}
function str_cut1($str,$start, $end) {//Get the first match, efficient, search and replace directly
$x = strpos($str, $start);
return substr($str, $x+strlen($start), strpos($str, $end)-$x+strlen($end));
}
function str_cut3($content,$start,$end){//Get the first match. The larger the string, the slower it will be!
$my = explode($start,$content);
$my = explode($end,$my[1]);
return $my[0];
}
The following is to extract all three matching functions (all original) to achieve the same collection purpose
function strcut($str,$start, $end) //Search the number first, Medium speed
{
if( strpos( $str , $start ) )
{
$sum = substr_count($str,$start);
$carr = array( );
for($i=0;$i<$sum;$i++){
$str = strstr($str, $start); $start));
$carr[] = substr($str, 0, strpos($str, $end));
🎜> return $carr;
}
function str_cut_all($str,$start, $end,$carr=array()) //Recursion, the slowest running efficiency!
{
if( strpos( $str, $start) )
{
$str = strstr( $str, $start);
$str = substr( $str, strlen( $ Start);
$ Carr [] = Substr ($ Str, 0, Strpos ($ Str, $ End));
If (STRPOS ($ Str, $ Start)) > return str_cut_all($str,$start, $end,$carr);
my_Ca($content ,$start,$end){//Get all matches, the fastest efficiency, because it is only read once, the larger the string, the more obvious it is
$m = explode($start,$content);
$a = array ();
for( $i = 1;$i < count($m);$i++ )
{
$my = explode($end,$m[$i]);
$a[] = $my[0];
unset($my);
}
return $a;
}
Note my-Ca comparison
If you write like this:
function my_Ca($content,$start,$end){//Get all matches
$m = explode($start,$content);
$a = array();
$sum = count($m);
for( $i = 1;$i < $sum;$i++ )
{
$my = explode($end ,$m[$i]);
$a[] = $my[0];
unset($my);
}
return $a;
}
The speed is faster again!
As can be seen from the above, it is not that the array processing function (explode) is slower than the string processing function (substr, etc.), nor is it faster than this, because when matching multiple data, matching The greater the array function, the greater the advantage. Processing strings is like cutting a cake into smaller pieces. Matching a single string using the cut method has the same effect (str_cut). The key still lies in---algorithm! The algorithm is well written, and all functions are the same!