提问人:Ali 提问时间:5/7/2009 最后编辑:IvarAli 更新时间:10/15/2023 访问量:985070
PHP 中的 startsWith() 和 endsWith() 函数
startsWith() and endsWith() functions in PHP
问:
我怎样才能编写两个函数,如果它以指定的字符/字符串开头或以它结尾,它们将接受一个字符串并返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
答:
function startsWith($haystack, $needle, $case = true) {
if ($case) {
return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}
return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}
function endsWith($haystack, $needle, $case = true) {
if ($case) {
return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}
return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}
归功于:
评论
PHP 8.0 及更高版本
从 PHP 8.0 开始,你可以使用
str_starts_with
手动和
str_ends_with
手动
例
echo str_starts_with($str, '|');
PHP 8.0 之前的版本
function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}
评论
return substr($haystack, -strlen($needle))===$needle;
$needle
if
$length
substr
return (substr($haystack, -$length, $length);
$length == 0
$haystack
到目前为止,所有答案似乎都做了大量不必要的工作,,等等。和函数返回 in 中第一次出现的索引:strlen calculations
string allocations (substr)
'strpos'
'stripos'
$needle
$haystack
function startsWith($haystack,$needle,$case=true)
{
if ($case)
return strpos($haystack, $needle, 0) === 0;
return stripos($haystack, $needle, 0) === 0;
}
function endsWith($haystack,$needle,$case=true)
{
$expectedPosition = strlen($haystack) - strlen($needle);
if ($case)
return strrpos($haystack, $needle, 0) === $expectedPosition;
return strripos($haystack, $needle, 0) === $expectedPosition;
}
评论
endsWith()
函数有错误。它的第一行应该是(不带 -1):$expectedPosition = strlen($haystack) - strlen($needle);
strpos($haystack, "$needle", 0)
json_decode()
strpos()
"
上面的正则表达式功能,但上面也建议了其他调整:
function startsWith($needle, $haystack) {
return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack);
}
function endsWith($needle, $haystack) {
return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
}
评论
我意识到这已经完成了,但你可能想看看strncmp,因为它允许你把字符串的长度进行比较,所以:
function startsWith($haystack, $needle, $case=true) {
if ($case)
return strncasecmp($haystack, $needle, strlen($needle)) == 0;
else
return strncmp($haystack, $needle, strlen($needle)) == 0;
}
评论
根据詹姆斯·布莱克的回答,以下是它的结尾版本:
function startsWith($haystack, $needle, $case=true) {
if ($case)
return strncmp($haystack, $needle, strlen($needle)) == 0;
else
return strncasecmp($haystack, $needle, strlen($needle)) == 0;
}
function endsWith($haystack, $needle, $case=true) {
return startsWith(strrev($haystack),strrev($needle),$case);
}
注意:我已将 if-else 部分换成 James Black 的 startsWith 函数,因为 strncasecmp 实际上是 strncmp 的不区分大小写的版本。
评论
strrev()
===
==
0
如果速度对您很重要,请尝试一下。(我相信这是最快的方法)
仅适用于字符串,并且$haystack只有 1 个字符
function startsWithChar($needle, $haystack)
{
return ($needle === $haystack[0]);
}
function endsWithChar($needle, $haystack)
{
return ($needle === $haystack[strlen($haystack) - 1]);
}
$str='|apples}';
echo startsWithChar('|',$str); //Returns true
echo endsWithChar('}',$str); //Returns true
echo startsWithChar('=',$str); //Returns false
echo endsWithChar('#',$str); //Returns false
评论
endsWithChar('','x')
Creative. Needles which contain haystacks.
您还可以使用正则表达式:
function endsWith($haystack, $needle, $case=true) {
return preg_match("/.*{$needle}$/" . (($case) ? "" : "i"), $haystack);
}
评论
preg_quote($needle, '/')
这是 PHP 4 的有效解决方案。如果在 PHP 5 上使用而不是 .substr_compare
strcasecmp(substr(...))
function stringBeginsWith($haystack, $beginning, $caseInsensitivity = false)
{
if ($caseInsensitivity)
return strncasecmp($haystack, $beginning, strlen($beginning)) === 0;
else
return strncmp($haystack, $beginning, strlen($beginning)) === 0;
}
function stringEndsWith($haystack, $ending, $caseInsensitivity = false)
{
if ($caseInsensitivity)
return strcasecmp(substr($haystack, strlen($haystack) - strlen($ending)), $haystack) === 0;
else
return strpos($haystack, $ending, strlen($haystack) - strlen($ending)) !== false;
}
简短易懂的单行代码,没有正则表达式。
startsWith() 是直截了当的。
function startsWith($haystack, $needle) {
return (strpos($haystack, $needle) === 0);
}
endsWith() 使用略显花哨和缓慢的 strrev():
function endsWith($haystack, $needle) {
return (strpos(strrev($haystack), strrev($needle)) === 0);
}
评论
已更新 23-Aug-2016
功能
function substr_startswith($haystack, $needle) {
return substr($haystack, 0, strlen($needle)) === $needle;
}
function preg_match_startswith($haystack, $needle) {
return preg_match('~' . preg_quote($needle, '~') . '~A', $haystack) > 0;
}
function substr_compare_startswith($haystack, $needle) {
return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function strpos_startswith($haystack, $needle) {
return strpos($haystack, $needle) === 0;
}
function strncmp_startswith($haystack, $needle) {
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
function strncmp_startswith2($haystack, $needle) {
return $haystack[0] === $needle[0]
? strncmp($haystack, $needle, strlen($needle)) === 0
: false;
}
测试
echo 'generating tests';
for($i = 0; $i < 100000; ++$i) {
if($i % 2500 === 0) echo '.';
$test_cases[] = [
random_bytes(random_int(1, 7000)),
random_bytes(random_int(1, 3000)),
];
}
echo "done!\n";
$functions = ['substr_startswith', 'preg_match_startswith', 'substr_compare_startswith', 'strpos_startswith', 'strncmp_startswith', 'strncmp_startswith2'];
$results = [];
foreach($functions as $func) {
$start = microtime(true);
foreach($test_cases as $tc) {
$func(...$tc);
}
$results[$func] = (microtime(true) - $start) * 1000;
}
asort($results);
foreach($results as $func => $time) {
echo "$func: " . number_format($time, 1) . " ms\n";
}
结果 (PHP 7.0.9)
(从快到慢排序)
strncmp_startswith2: 40.2 ms
strncmp_startswith: 42.9 ms
substr_compare_startswith: 44.5 ms
substr_startswith: 48.4 ms
strpos_startswith: 138.7 ms
preg_match_startswith: 13,152.4 ms
结果 (PHP 5.3.29)
(从快到慢排序)
strncmp_startswith2: 477.9 ms
strpos_startswith: 522.1 ms
strncmp_startswith: 617.1 ms
substr_compare_startswith: 706.7 ms
substr_startswith: 756.8 ms
preg_match_startswith: 10,200.0 ms
评论
function startswith5b($haystack, $needle) {return ($haystack{0}==$needle{0})?strncmp($haystack, $needle, strlen($needle)) === 0:FALSE;}
$haystack[0]
如果不使用 isset 对其进行测试,将抛出通知错误。针头也是如此。但是,如果添加测试,则会降低其性能
该函数可以在许多特殊情况下返回,所以这是我的版本,它处理这些问题:substr
false
function startsWith( $haystack, $needle ){
return $needle === ''.substr( $haystack, 0, strlen( $needle )); // substr's false => empty string
}
function endsWith( $haystack, $needle ){
$len = strlen( $needle );
return $needle === ''.substr( $haystack, -$len, $len ); // ! len=0
}
测试(表示良好):true
var_dump( startsWith('',''));
var_dump( startsWith('1',''));
var_dump(!startsWith('','1'));
var_dump( startsWith('1','1'));
var_dump( startsWith('1234','12'));
var_dump(!startsWith('1234','34'));
var_dump(!startsWith('12','1234'));
var_dump(!startsWith('34','1234'));
var_dump('---');
var_dump( endsWith('',''));
var_dump( endsWith('1',''));
var_dump(!endsWith('','1'));
var_dump( endsWith('1','1'));
var_dump(!endsWith('1234','12'));
var_dump( endsWith('1234','34'));
var_dump(!endsWith('12','1234'));
var_dump(!endsWith('34','1234'));
此外,该功能也值得一看。http://www.php.net/manual/en/function.substr-compare.phpsubstr_compare
总之:
function startsWith($str, $needle){
return substr($str, 0, strlen($needle)) === $needle;
}
function endsWith($str, $needle){
$length = strlen($needle);
return !$length || substr($str, - $length) === $needle;
}
您可以使用substr_compare
函数来检查 start-with 和 ends-with:
function startsWith($haystack, $needle) {
return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function endsWith($haystack, $needle) {
return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
这应该是 PHP 7(基准测试脚本)上最快的解决方案之一。针对 8KB 干草堆、各种长度的针以及完整、部分和无匹配情况进行了测试。strncmp
的 starts-with 速度更快,但它不能检查 ends-with。
评论
strrpos
-strlength($haystack)
!== false
xxxyyy
yyy
strrpos
x
!== false
strrpos
strpos
$temp
!== false
=== 0
=== $temp
为什么不是以下?
//How to check if a string begins with another string
$haystack = "valuehaystack";
$needle = "value";
if (strpos($haystack, $needle) === 0){
echo "Found " . $needle . " at the beginning of " . $haystack . "!";
}
输出:
在valuehaystack的开头发现了价值!
请记住,如果在大海捞针中未找到针,则返回 false,当且仅当在索引 0(又名开头)找到针时,将返回 0。strpos
这里结束了:
$haystack = "valuehaystack";
$needle = "haystack";
//If index of the needle plus the length of the needle is the same length as the entire haystack.
if (strpos($haystack, $needle) + strlen($needle) === strlen($haystack)){
echo "Found " . $needle . " at the end of " . $haystack . "!";
}
在这种情况下,不需要函数 startsWith() 作为
(strpos($stringToSearch, $doesItStartWithThis) === 0)
将准确返回 true 或 false。
这似乎很奇怪,它就是这么简单,所有狂野的功能都在这里猖獗。
评论
strpos()
strncmp()
这可能有效
function startsWith($haystack, $needle) {
return substr($haystack, 0, strlen($needle)) == $needle;
}
来源: https://stackoverflow.com/a/4419658
专注于 startswith,如果您确定字符串不为空,则在第一个字符、比较之前、strlen 等处添加测试,可以加快速度:
function startswith5b($haystack, $needle) {
return ($haystack{0}==$needle{0})?strncmp($haystack, $needle, strlen($needle)) === 0:FALSE;
}
它以某种方式(20%-30%)快。添加另一个字符测试,如 $haystack{1}===$needle{1} 似乎不会加快速度,甚至可能减慢速度。
===
似乎比条件运算符更快==
(a)?b:c
if(a) b; else c;
对于那些问“为什么不使用strpos?”的人,称其他解决方案是“不必要的工作”
strpos 速度很快,但它不是这项工作的正确工具。
为了理解,这里有一个小小的模拟作为例子:
Search a12345678c inside bcdefga12345678xbbbbb.....bbbbba12345678c
计算机“内部”做什么?
With strccmp, etc...
is a===b? NO
return false
With strpos
is a===b? NO -- iterating in haysack
is a===c? NO
is a===d? NO
....
is a===g? NO
is a===g? NO
is a===a? YES
is 1===1? YES -- iterating in needle
is 2===3? YES
is 4===4? YES
....
is 8===8? YES
is c===x? NO: oh God,
is a===1? NO -- iterating in haysack again
is a===2? NO
is a===3? NO
is a===4? NO
....
is a===x? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
...
... may many times...
...
is a===b? NO
is a===a? YES -- iterating in needle again
is 1===1? YES
is 2===3? YES
is 4===4? YES
is 8===8? YES
is c===c? YES YES YES I have found the same string! yay!
was it at position 0? NOPE
What you mean NO? So the string I found is useless? YEs.
Damn.
return false
假设 strlen 不迭代整个字符串(但即使在这种情况下),这也不方便。
评论
下面是两个不引入临时字符串的函数,当针非常大时,这可能很有用:
function startsWith($haystack, $needle)
{
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
function endsWith($haystack, $needle)
{
return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
评论
endsWidth
return $needle==='' || substr_compare(
-strlen($needle)===0
endsWith('a','')
false
endsWith('', 'foo')
substr_compare()
|| (strlen($needle) <= strlen($haystack) && substr_compare(
) === 0);
return $needle === '' || @substr_compare(
我希望下面的答案可能是有效的,也是简单的:
$content = "The main string to search";
$search = "T";
//For compare the begining string with case insensitive.
if(stripos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the begining string with case sensitive.
if(strpos($content, $search) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case insensitive.
if(stripos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
//For compare the ending string with case sensitive.
if(strpos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';
前面的许多答案也同样有效。但是,这可能尽可能短,并让它做你想做的事。你只是声明你希望它“返回真实”。因此,我包含了返回布尔值 true/false 和文本 true/false 的解决方案。
// boolean true/false
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0 ? 1 : 0;
}
function endsWith($haystack, $needle)
{
return stripos($haystack, $needle) === 0 ? 1 : 0;
}
// textual true/false
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0 ? 'true' : 'false';
}
function endsWith($haystack, $needle)
{
return stripos($haystack, $needle) === 0 ? 'true' : 'false';
}
评论
'true'
'false'
true
我会这样做
function startWith($haystack,$needle){
if(substr($haystack,0, strlen($needle))===$needle)
return true;
}
function endWith($haystack,$needle){
if(substr($haystack, -strlen($needle))===$needle)
return true;
}
评论
这些天我通常最终会使用像 underscore-php 这样的库。
require_once("vendor/autoload.php"); //use if needed
use Underscore\Types\String;
$str = "there is a string";
echo( String::startsWith($str, 'the') ); // 1
echo( String::endsWith($str, 'ring')); // 1
该库充满了其他方便的功能。
$bStartsWith = strpos($sHaystack, $sNeedle) == 0;
$bEndsWith = strrpos($sHaystack, $sNeedle) == strlen($sHaystack)-strlen($sNeedle);
评论
strpos($sHaystack, $sNeedle) == 0
strpos($sHaystack, $sNeedle) === 0
false == 0
true
$ends_with = strrchr($text, '.'); // Ends with dot
$start_with = (0 === strpos($text, '.')); // Starts with dot
评论
这个问题已经有很多答案,但在某些情况下,你可以满足于比所有答案更简单的东西。 如果您要查找的字符串是已知的(硬编码),则可以使用正则表达式而不使用任何引号等。
检查字符串是否以“ABC”开头:
preg_match('/^ABC/', $myString); // "^" here means beginning of string
以“ABC”结尾:
preg_match('/ABC$/', $myString); // "$" here means end of string
在我的简单案例中,我想检查字符串是否以斜杠结尾:
preg_match('#/$#', $myPath); // Use "#" as delimiter instead of escaping slash
优点:由于它非常简短和简单,因此您不必定义如上所示的函数(例如 )。endsWith()
但同样,这并不是针对所有情况的解决方案,只是针对这个非常具体的情况。
评论
做得更快:
function startsWith($haystack,$needle) {
if($needle==="") return true;
if($haystack[0]<>$needle[0]) return false; // ------------------------- speed boost!
return (0===substr_compare($haystack,$needle,0,strlen($needle)));
}
额外的一行,比较字符串的第一个字符,可以使 错误大小写会立即返回,因此会进行许多比较 速度快得多(我测量时快 7 倍)。在真实的情况下,您几乎不需要为这条线付出任何性能代价,所以我认为它值得一提。(此外,在实践中,当您为特定的起始块测试多个字符串时,大多数比较都会失败,因为在典型情况下,您正在寻找某些东西。
注意:下面 @Tino 评论中的错误已修复
至于字符串与整数
如果要强制字符串比较(即,您期望 startsWith(“1234”,12) 为 true),则需要进行一些类型转换:
function startsWith($haystack,$needle) {
if($needle==="") return true;
$haystack = (string)$haystack;
$needle = (string)$needle;
if($haystack[0]<>$needle[0]) return false; // ------------------------- speed boost!
return (0===substr_compare($haystack,$needle,0,strlen($needle)));
}
我不认为这是必要的,但这是一个有趣的边缘情况,导致诸如“布尔值是否以t开头?”这样的问题 - 所以你决定,但要确保你决定永远。
评论
startsWith("123", "0")
true
mpen 的答案非常彻底,但不幸的是,提供的基准有一个非常重要且有害的疏忽。
因为针和干草堆中的每个字节都是完全随机的,所以针-干草堆对在第一个字节上不同的概率是 99.609375%,这意味着平均而言,100000 对中约有 99609 个在第一个字节上会不同。换句话说,基准测试严重偏向于显式检查第一个字节的实现,就像一样。startswith
strncmp_startswith2
如果测试生成循环按如下方式实现:
echo 'generating tests';
for($i = 0; $i < 100000; ++$i) {
if($i % 2500 === 0) echo '.';
$haystack_length = random_int(1, 7000);
$haystack = random_bytes($haystack_length);
$needle_length = random_int(1, 3000);
$overlap_length = min(random_int(0, $needle_length), $haystack_length);
$needle = ($needle_length > $overlap_length) ?
substr($haystack, 0, $overlap_length) . random_bytes($needle_length - $overlap_length) :
substr($haystack, 0, $needle_length);
$test_cases[] = [$haystack, $needle];
}
echo " done!<br />";
基准测试结果讲述了一个略有不同的故事:
strncmp_startswith: 223.0 ms
substr_startswith: 228.0 ms
substr_compare_startswith: 238.0 ms
strncmp_startswith2: 253.0 ms
strpos_startswith: 349.0 ms
preg_match_startswith: 20,828.7 ms
当然,这个基准测试可能仍然不是完全无偏的,但它在给定部分匹配的针头时也测试了算法的效率。
这是已接受答案的多字节安全版本,它适用于 UTF-8 字符串:
function startsWith($haystack, $needle)
{
$length = mb_strlen($needle, 'UTF-8');
return (mb_substr($haystack, 0, $length, 'UTF-8') === $needle);
}
function endsWith($haystack, $needle)
{
$length = mb_strlen($needle, 'UTF-8');
return $length === 0 ||
(mb_substr($haystack, -$length, $length, 'UTF-8') === $needle);
}
评论
startsWith
$length = mb_strlen($needle, 'UTF-8');
最快的 endsWith() 解决方案:
# Checks if a string ends in a string
function endsWith($haystack, $needle) {
return substr($haystack,-strlen($needle))===$needle;
}
基准:
# This answer
function endsWith($haystack, $needle) {
return substr($haystack,-strlen($needle))===$needle;
}
# Accepted answer
function endsWith2($haystack, $needle) {
$length = strlen($needle);
return $length === 0 ||
(substr($haystack, -$length) === $needle);
}
# Second most-voted answer
function endsWith3($haystack, $needle) {
// search forward starting from end minus needle length characters
if ($needle === '') {
return true;
}
$diff = \strlen($haystack) - \strlen($needle);
return $diff >= 0 && strpos($haystack, $needle, $diff) !== false;
}
# Regex answer
function endsWith4($haystack, $needle) {
return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
}
function timedebug() {
$test = 10000000;
$time1 = microtime(true);
for ($i=0; $i < $test; $i++) {
$tmp = endsWith('TestShortcode', 'Shortcode');
}
$time2 = microtime(true);
$result1 = $time2 - $time1;
for ($i=0; $i < $test; $i++) {
$tmp = endsWith2('TestShortcode', 'Shortcode');
}
$time3 = microtime(true);
$result2 = $time3 - $time2;
for ($i=0; $i < $test; $i++) {
$tmp = endsWith3('TestShortcode', 'Shortcode');
}
$time4 = microtime(true);
$result3 = $time4 - $time3;
for ($i=0; $i < $test; $i++) {
$tmp = endsWith4('TestShortcode', 'Shortcode');
}
$time5 = microtime(true);
$result4 = $time5 - $time4;
echo $test.'x endsWith: '.$result1.' seconds # This answer<br>';
echo $test.'x endsWith2: '.$result4.' seconds # Accepted answer<br>';
echo $test.'x endsWith3: '.$result2.' seconds # Second most voted answer<br>';
echo $test.'x endsWith4: '.$result3.' seconds # Regex answer<br>';
exit;
}
timedebug();
基准测试结果:
10000000x endsWith: 1.5760900974274 seconds # This answer
10000000x endsWith2: 3.7102129459381 seconds # Accepted answer
10000000x endsWith3: 1.8731069564819 seconds # Second most voted answer
10000000x endsWith4: 2.1521229743958 seconds # Regex answer
评论
无复制和无实习循环:
function startsWith(string $string, string $start): bool
{
return strrpos($string, $start, - strlen($string)) !== false;
}
function endsWith(string $string, string $end): bool
{
return ($offset = strlen($string) - strlen($end)) >= 0
&& strpos($string, $end, $offset) !== false;
}
评论
为此,您可以使用 fnmatch 函数。
// Starts with.
fnmatch('prefix*', $haystack);
// Ends with.
fnmatch('*suffix', $haystack);
评论
PHP 8 更新
PHP 8 包含新的 str_starts_with
和 str_ends_with
函数,最终为此问题提供了高效且方便的解决方案:
$str = "beginningMiddleEnd";
if (str_starts_with($str, "beg")) echo "printed\n";
if (str_starts_with($str, "Beg")) echo "not printed\n";
if (str_ends_with($str, "End")) echo "printed\n";
if (str_ends_with($str, "end")) echo "not printed\n";
此功能的 RFC 提供了更多信息,并讨论了明显(和不那么明显)的用户空间实现的优点和问题。
function startsWith($haystack, $needle)
{
$length = mb_strlen($needle);
return mb_substr($haystack, 0, $length) === $needle;
}
function endsWith($haystack, $needle)
{
$length = mb_strlen($needle);
if(!$length)
{
return true;
}
return mb_substr($haystack, -$length) === $needle;
}
字符串长度和字符定位是多字节与单字节可以发挥作用的两个示例。PHP 中的标准字符串是 char 数组,就像在 C 中一样,它们始终是单字节。因此,如果 UTF-16,普通 strlen 字符串 () 中的第三个字符实际上是第二个字符的开头。如果在字符串的开头寻找字符串是否可以是 JSON,这没什么大不了的,因为这是一个有效的单字节字符,例如在 ASCII 编码中,但如果检查字符串末尾的 emogi 👍 vs 😲 判断反应,那就另当别论了,因为它们是多字节字符。str[2]
{
{
拉拉维尔 9.0
如果你正在使用 Laravel,那么你可以执行以下操作(如果你没有使用 Laravel,你真的应该这样做)。
Str::of('a long string')->startsWith('a');
Str::of('a long string')->endsWith('string');
//true
//true
我的任务是为打开的CMS EffCore创建最近似的str_starts_with()polyfill,结果是以下代码:
namespace {
if (!function_exists('str_starts_with')) {
function str_starts_with($haystack, $needle) {
if (is_null ($haystack)) trigger_error('str_starts_with(): Passing null to parameter #1 ($haystack) of type string is deprecated in '.__FILE__, E_USER_DEPRECATED);
if (is_null ($needle) ) trigger_error('str_starts_with(): Passing null to parameter #2 ($needle) of type string is deprecated in '.__FILE__, E_USER_DEPRECATED);
if (is_array ($haystack)) throw new TypeError('str_starts_with(): Argument #1 ($haystack) must be of type string, array given');
if (is_object ($haystack)) throw new TypeError('str_starts_with(): Argument #1 ($haystack) must be of type string, object given');
if (is_resource($haystack)) throw new TypeError('str_starts_with(): Argument #1 ($haystack) must be of type string, resource given');
if (is_array ($needle) ) throw new TypeError('str_starts_with(): Argument #2 ($needle) must be of type string, array given');
if (is_object ($needle) ) throw new TypeError('str_starts_with(): Argument #2 ($needle) must be of type string, object given');
if (is_resource($needle) ) throw new TypeError('str_starts_with(): Argument #2 ($needle) must be of type string, resource given');
if ((string)$needle === '') return true;
return strpos((string)$haystack, (string)$needle) === 0;
}
}
}
测试数据:
str_starts_with('100', '') # true
str_starts_with('100', '1') # true
str_starts_with('100', '0') # false
str_starts_with('100', 0) # false
str_starts_with('100', 1) # true
str_starts_with('100', 0.0) # false
str_starts_with('100', 1.0) # true
str_starts_with('100', true) # true / (string)true === '1'
str_starts_with('100', false) # true / (string)false === ''
str_starts_with('100', null) # Warning
str_starts_with('100', []) # Exception
str_starts_with('100', [0]) # Exception
str_starts_with('100', [1]) # Exception
str_starts_with('100', new stdCLass) # Exception
str_starts_with('100', new SomeClass) # Exception
str_starts_with('100', fopen('resource') # Exception
str_starts_with('010', '') # true
str_starts_with('010', '1') # false
str_starts_with('010', '0') # true
str_starts_with('010', 0) # true
str_starts_with('010', 1) # false
str_starts_with('010', 0.0) # true
str_starts_with('010', 1.0) # false
str_starts_with('010', true) # false / (string)true === '1'
str_starts_with('010', false) # true / (string)false === ''
str_starts_with('010', null) # Warning
str_starts_with('010', []) # Exception
str_starts_with('010', [0]) # Exception
str_starts_with('010', [1]) # Exception
str_starts_with('010', new stdCLass) # Exception
str_starts_with('010', new SomeClass) # Exception
str_starts_with('010', fopen('resource') # Exception
str_starts_with('', '1') # false
str_starts_with('100', '1') # true
str_starts_with('010', '1') # false
str_starts_with('001', '1') # false
str_starts_with(0, '1') # false
str_starts_with(1, '1') # true
str_starts_with(0.0, '1') # false
str_starts_with(1.0, '1') # true
str_starts_with(true, '1') # true / (string)true === '1'
str_starts_with(false, '1') # false / (string)false === ''
str_starts_with(null, '1') # Warning
str_starts_with([], '1') # Exception
str_starts_with([0], '1') # Exception
str_starts_with([1], '1') # Exception
str_starts_with(new stdCLass, '1') # Exception
str_starts_with(new SomeClass, '1') # Exception
str_starts_with(fofopen('resource'), '1') # Exception
评论
s($str)->startsWith
('|') 和 s($str)->endsWith('}')
很有帮助,正如这个独立库中所找到的那样。str_starts_with
str_end_with