在php中,检查字符串是否由三个或多个破折号组成的最快方法是什么


What it the fastest way to check if a string consists of three or more dashes in php?

regex是唯一的方法吗?它慢吗?

像这样的东西?

preg_match("/^('-){3,}/", $string);

只有短划线

如果您希望字符串只有短划线,并且必须有3个或更多:

$match = (preg_match('/^-{3,}$/', $string) === 1);

另一种没有正则表达式的方法似乎慢了25%(issetstrlen慢):

$match = (count_chars($string, 3) === '-' && isset($string[2]));

相邻虚线

如果您希望在一行中有3个或更多破折号,但可能有其他字符(例如foo---bar):

$match = (strpos($string, '---') !== false);

一些破折号

如果您想在任何位置使用3个或更多破折号(例如-foo-bar-):

$match = (substr_count($string, '-') >= 3);

有substra_count函数。可能有利于计数字符

echo substr_count('fa-r-r', '-'); // outputs 2

您可以这样做:

function dashtest($str) {
   $rep = str_replace('-', '', $str);
   $length = strlen($str);
   return ( $length>2 && $rep =='' ) ? true : false;
}

另一种方式:

function dashtest($str) {
    for ($i=0 ; $i<strlen($str); $i++) {
        if ($str[$i]!='-') return false;
    }
    if ($i<3) return false;
    return true;
}

正则表达式方式:

if (preg_match('~^-{3,}+$~', $str)) { /*true*/} else { /*false*/}

我运行了这个测试,有趣的是regex是最快的

<?php

function dashtest($str) {
   $rep = str_replace( '-', '', $str );
   $length = strlen( $str );
   return ( $length < 3 || $rep != '' ) ? false : true;
}
function dashtest2($str) {
    for ($i=0 ; $i<strlen($str); $i++) {
        if ($str[$i]!='-') return false;
    }
    if ($i<3) return false;
    return true;
}

$string = '------------';

$start = microtime(true);
for ( $i=0; $i<100000; $i++ ) {
    dashtest( $string );
}
echo microtime(true) - $start;
echo "'n";

$start = microtime(true);
for ( $i=0; $i<100000; $i++ ) {
    dashtest2( $string );
}
echo microtime(true) - $start;
echo "'n";

$start = microtime(true);
for ( $i=0; $i<100000; $i++ ) {
    (preg_match('/^-{3,}$/', $string) === 1);
}
echo microtime(true) - $start;
echo "'n";

输出:

0.38635802268982

1.5208051204681<-哈哈!

0.15313696861267

再次尝试

$string = '----------------------------------------------------------------------------';

0.52067899703979

8.7124900817871

0.17864608764648

regex再次赢得