PHP startsWith()和endsWith()函数用法示例

2021年4月17日18:02:22 发表评论 776 次浏览

startsWith()函数

StartsWith()函数用于测试字符串是否以给定的字符串开头。该函数不区分大小写, 并且返回布尔值。此功能可与过滤器功能一起使用以搜索数据。

语法

bool startsWith( string, startString )

参数:此函数接受上述和以下所述的两个参数:

  • 串:此参数用于保存需要测试的文本。
  • startString:要在String开头搜索的文本。如果为空字符串, 则返回true。

返回值:

如果成功, 此函数返回True;如果失败, 则返回False。

示例1:

<?php
  
//Function to check string starting
//with given substring
function startsWith ( $string , $startString )
{
     $len = strlen ( $startString );
     return ( substr ( $string , 0, $len ) === $startString );
}
  
//Main function
if (startsWith( "abcde" , "c" ))
     echo "True" ;
else
     echo "False" ;
?>

输出如下:

False

示例2:

<?php
  
//Function to check string starting
//with given substring
function startsWith ( $string , $startString )
{
     $len = strlen ( $startString );
     return ( substr ( $string , 0, $len ) === $startString );
}
  
//Main function
if (startsWith( "abcde" , "a" ))
     echo "True" ;
else
     echo "False" ;
?>

输出如下:

True

EndsWith()函数

startsWith()函数用于测试字符串是否以给定的字符串结尾。该函数不区分大小写, 并且返回布尔值。 endsWith()函数可与Filter函数一起使用以搜索数据。

语法如下:

bool endsWith( string, endString )

参数:

  • 串:此参数保存需要测试的文本。
  • endString:在给定String的末尾要搜索的文本。如果为空字符串, 则返回true。

返回值:如果成功, 此函数返回True;如果失败, 则返回False。

示例1:

<?php
  
//Function to check the string is ends 
//with given substring or not
function endsWith( $string , $endString )
{
     $len = strlen ( $endString );
     if ( $len == 0) {
         return true;
     }
     return ( substr ( $string , - $len ) === $endString );
}
  
//Driver code
if (endsWith( "abcde" , "de" ))
     echo "True" ;
else
     echo "False" ;
?>

输出如下:

True

示例2:

<?php
  
//Function to check the string is ends 
//with given substring or not
function endsWith( $string , $endString )
{
     $len = strlen ( $endString );
     if ( $len == 0) {
         return true;
     }
     return ( substr ( $string , - $len ) === $endString );
}
  
//Driver code
if (endsWith( "abcde" , "dgfe" ))
     echo "True" ;
else
     echo "False" ;
?>

输出如下:

False

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: