在php中查找子字符串的最有效方法

时间:2016-02-17 16:51:09

标签: php

我在招聘流程技能测试期间遇到了以下问题:

  

假设一个大的随机字符串,例如:

     

$x = str_shuffle(str_repeat(implode('', range('a', 'z')), 1000000));

     

查找子字符串的最有效方法是什么?

我想知道答案只是为了了解它。

事先谢谢!

2 个答案:

答案 0 :(得分:2)

你可以这样做:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
   echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}

答案 1 :(得分:2)

您拥有的选项是:

strpos()preg_match()用于正则表达式匹配,stripos()用于不区分大小写搜索。

正则字符串匹配总是比普通字符串搜索慢。但这是一个比较,考虑PHP的普通安装中的案例性或不敏感的字符串:

此数据来自10000字符串中的1k次搜索。

php5-cgi        strpos()        27.7 ms
mod_php5        strpos()        30.6 ms
mod_php5 + ZP   strpos()        37.2 ms
php5-cgi        stripos()       163.6 ms
mod_php5        stripos()       172.8 ms
mod_php5 + ZP   stripos()       177.3 ms
php5-cgi        preg_match()    72.2 ms

Source

相关问题