很简单,但我无法让确切的语法正常工作。
我只是想要一个真假检查,看看一个字符串是否带有'for the'(不区分大小写)。
如果只是这样,那么您可以使用纯文本搜索:
if (stripos("for the", $text) === 0) { // case-insensitive here
// string starts with "for the"
}
或者,
if (substr($text, 0, 7) == "for the")
下面的评论让我想知道哪个实际上更快,所以我写了一些基准测试。
这是 TLDR 版本:
strpos
如果你不使用大字符串,它真的很快。strncmp
可靠且快速。preg_match
从来都不是一个好的选择。这是长版本:
for ($i = 0, $l = strlen($needle); $i < $l; ++$i) {
if ($needle{$i} !== $haystack{$i}) return false;
}
return true;
有趣的点:
strpos
在长的、完全不匹配的针上与短的干草堆进行测试。
strpos
记录了前 11 次。strpos
性能最好,但它被长长的干草堆上长长的不匹配的针头压得喘不过气来。它们比大多数测试慢 5-10 倍。strncmp
快速且最一致。preg_match
始终比其他功能慢约 2 倍Haystack: 83 characters
______________________________________________________________
____________|__________ non-matching ___________|_______ matching ________|
| function | 1 | 5 | 82 | 83 | 1 | 5 | 83 |
|------------+--------+--------+--------+--------+--------+--------+--------|
| manual | 0.2291 | 0.2222 | 0.2266 | 4.1523 | 0.2337 | 0.4263 | 4.1972 |
| preg_match | 0.3622 | 0.3792 | 0.4098 | 0.4656 | 0.3642 | 0.3694 | 0.4658 |
| strncmp | 0.1860 | 0.1918 | 0.1881 | 0.1981 | 0.1841 | 0.1857 | 0.1980 |
| strpos | 0.1596 | 0.1633 | 0.1537 | 0.1560 | 0.1571 | 0.1589 | 0.1681 |
| substr | 0.2052 | 0.2066 | 0.2009 | 0.2166 | 0.2061 | 0.2017 | 0.2236 |
-----------------------------------------------------------------------------
Haystack: 10000 characters
______________________________________________________________
____________|__________ non-matching ___________|_______ matching ________|
| function | 1 | 5 | 82 | 83 | 1 | 5 | 83 |
|------------+--------+--------+--------+--------+--------+--------+--------|
| manual | 0.2275 | 0.2249 | 0.2278 | 4.1507 | 0.2315 | 0.4233 | 4.1834 |
| preg_match | 0.3597 | 0.3628 | 0.4147 | 0.4654 | 0.3662 | 0.3679 | 0.4684 |
| strncmp | 0.1886 | 0.1914 | 0.1835 | 0.2014 | 0.1851 | 0.1854 | 0.1989 |
| strpos | 0.1605 | 2.1877 | 2.3737 | 0.5933 | 0.1575 | 0.1597 | 0.1667 |
| substr | 0.2073 | 0.2085 | 0.2017 | 0.2152 | 0.2036 | 0.2090 | 0.2183 |
-----------------------------------------------------------------------------
您想用来^
表示字符串的开头:
$string_one = "For the love of Mike";
$string_two = "for the amazing reason.";
$match = preg_match("/^for the/i", $string_one); // Outputs 1
$match = preg_match("/^for the/i", $string_two); // Outputs 1
这/i
是使搜索不区分大小写的部分。
怎么样
if(preg_match("/^for the/", $yourString))
{
return true;
}
else
{
return false;
}
注意 , 的代码^
匹配字符串的开头。
如果您已阅读文档中的第一个示例,您就会看到答案。
if ( preg_match('/^for the/i', $sentence) )
{
// a match was found
}
正则表达式是/^for the/i