php 如何在PHP中检查字符串是否以“_”开头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1962031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:28:10  来源:igfitidea点击:

How to check if a string starts with "_" in PHP?

php

提问by openfrog

Example: I have a $variable = "_foo", and I want to make absolutely sure that $variable does not start with an underscore "_". How can I do that in PHP? Is there some access to the char array behind the string?

示例:我有一个$variable = "_foo", 我想绝对确保 $variable 不以下划线开头"_"。我怎样才能在 PHP 中做到这一点?是否可以访问字符串后面的字符数组?

回答by Peter Porfy

$variable[0] != "_"

How does it work?

它是如何工作的?

In PHP you can get particular character of a string with array index notation. $variable[0]is the first character of a string (if $variable is a string).

在 PHP 中,您可以使用数组索引符号获取字符串的特定字符。$variable[0]是字符串的第一个字符(如果 $variable 是字符串)。

回答by Alex Sexton

You might check out the substrfunction in php and grab the first character that way:

您可以查看substrphp 中的函数并以这种方式获取第一个字符:

http://php.net/manual/en/function.substr.php

http://php.net/manual/en/function.substr.php

if (substr('_abcdef', 0, 1) === '_') { ... }

回答by Gordon

Since someone mentioned efficiency, I've benchmarked the functions given so far out of curiosity:

由于有人提到效率,出于好奇,我对迄今为止给出的函数进行了基准测试:

function startsWith1($str, $char) {
    return strpos($str, $char) === 0;
}
function startsWith2($str, $char) {
    return stripos($str, $char) === 0;
}
function startsWith3($str, $char) {
    return substr($str, 0, 1) === $char;
}
function startsWith4($str, $char){
    return $str[0] === $char;
}
function startsWith5($str, $char){
    return (bool) preg_match('/^' . $char . '/', $str);
}
function startsWith6($str, $char) {
    if (is_null($encoding)) $encoding = mb_internal_encoding();
    return mb_substr($str, 0, mb_strlen($char, $encoding), $encoding) === $char;
}

Here are the results on my average DualCore machine with 100.000 runs each

这是我的平均 DualCore 机器的结果,每台机器运行 100.000 次

// Testing '_string'
startsWith1 took 0.385906934738
startsWith2 took 0.457293987274
startsWith3 took 0.412894964218
startsWith4 took 0.366240024567 <-- fastest
startsWith5 took 0.642996072769
startsWith6 took 1.39859509468

// Tested "string"
startsWith1 took 0.384965896606
startsWith2 took 0.445554971695
startsWith3 took 0.42377281189
startsWith4 took 0.373164176941 <-- fastest
startsWith5 took 0.630424022675
startsWith6 took 1.40699005127

// Tested 1000 char random string [a-z0-9]
startsWith1 took 0.430691003799
startsWith2 took 4.447286129
startsWith3 took 0.413349866867
startsWith4 took 0.368592977524 <-- fastest
startsWith5 took 0.627470016479
startsWith6 took 1.40957403183

// Tested 1000 char random string [a-z0-9] with '_' prefix
startsWith1 took 0.384054899216
startsWith2 took 4.41522812843
startsWith3 took 0.408898115158
startsWith4 took 0.363884925842 <-- fastest
startsWith5 took 0.638479948044
startsWith6 took 1.41304707527

As you can see, treating the haystack as array to find out the char at the first position is always the fastestsolution. It is also always performing at equal speed, regardless of string length. Using strposis faster than substrfor short strings but slower for long strings, when the string does not start with the prefix. The difference is irrelevant though. striposis incrediblyslow with long strings. preg_matchperforms mostly the same regardless of string length, but is only mediocre in speed. The mb_substrsolution performs worst, while probably being more reliable though.

如您所见,将 haystack 视为数组以找出第一个位置的字符始终是最快的解决方案。无论琴弦长度如何,它也始终以相同的速度执行。当字符串不以前缀开头时,使用strpossubstr短字符串快但长字符串慢。区别虽然无关紧要。stripos令人难以置信的长字符串慢。preg_match无论字符串长度如何,其性能大致相同,但速度一般。该mb_substr解决方案的性能最差,但可能更可靠。

Given that these numbers are for 100.000 runs, it should be obvious that we are talking about 0.0000x seconds per call. Picking one over the other for efficiencyis a worthless micro-optimization, unless your app is doing startsWithchecking for a living.

鉴于这些数字是针对 100.000 次运行的,很明显我们在谈论每次调用 0.0000x 秒。选择一个来提高效率是一种毫无价值的微观优化,除非您的应用程序以startsWith检查为生。

回答by Anon343224user

This is the most simple answer where you are not concerned about performance:

这是您不关心性能的最简单的答案:

if (strpos($string, '_') === 0) {
    # code
}

If strpos returns 0it means that what you were looking for begins at character 0, the start of the string.

如果 strpos 返回,0则表示您要查找的内容始于 character 0,即字符串的开头。

It is documented thoroughly here: http://uk3.php.net/manual/en/function.strpos.php

此处详细记录:http: //uk3.php.net/manual/en/function.strpos.php

(PS $string[0] === '_'is the best answer)

(PS$string[0] === '_'为最佳答案)

回答by miku

function starts_with($s, $prefix){
    // returns a bool
    return strpos($s, $prefix) === 0;
}

starts_with($variable, "_");

回答by Gumbo

Here's a better starts withfunction:

这是一个更好的开始函数:

function mb_startsWith($str, $prefix, $encoding=null) {
    if (is_null($encoding)) $encoding = mb_internal_encoding();
    return mb_substr($str, 0, mb_strlen($prefix, $encoding), $encoding) === $prefix;
}

回答by Carson Myers

To build on pinusnegra's answer, and in response to Gumbo's comment on that answer:

以 pinusnegra 的答案为基础,并回应 Gumbo 对该答案的评论:

function has_leading_underscore($string) {

    return $string[0] === '_';

}

Running on PHP 5.3.0, the following works and returns the expected value, even without checking if the string is at least 1 character in length:

在 PHP 5.3.0 上运行,即使不检查字符串的长度是否至少为 1 个字符,以下代码也能正常工作并返回预期值:

echo has_leading_underscore('_somestring').', ';
echo has_leading_underscore('somestring').', ';
echo has_leading_underscore('').', ';
echo has_leading_underscore(null).', ';
echo has_leading_underscore(false).', ';
echo has_leading_underscore(0).', ';
echo has_leading_underscore(array('_foo', 'bar'));

/*
 * output: true, false, false, false, false, false, false
 */

I don't know how other versions of PHP will react, but if they all work, then this method is probably more efficient than the substr route.

我不知道其他版本的 PHP 会如何反应,但如果它们都有效,那么这种方法可能比 substr 路由更有效。