您的位置:

PHP如何判断字符串是否存在某个字符串

在开发过程中,常常需要判断一个字符串是否包含另外一个字符串。PHP提供了多个函数可以实现这个功能,本文将从多个方面对PHP判断字符串是否存在某个字符串做出详细的阐述。

一、strpos函数

PHP的strpos函数可以用来在一个字符串中查找另一个字符串第一次出现的位置。函数原型如下:

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

其中,haystack参数为要搜索的字符串,needle参数为要查找的字符串,offset参数为起始搜索位置。

如果找到了要查找的字符串,strpos函数将返回它在原字符串中首次出现的位置(位置从0开始数)。如果没找到,则返回false。

以下是一个例子:

$mystring = 'hello world';
$findme   = 'world';
$pos = strpos($mystring, $findme);
if ($pos !== false) {
    echo "字符串 '$findme' 在字符串 '$mystring' 中被发现

"; echo "它在字符串 $mystring 的位置是 $pos

"; } else { echo '抱歉,没有找到字符串。'; }

上述代码的输出结果为:
字符串 'world' 在字符串 'hello world' 中被发现
它在字符串 hello world 的位置是 6

二、preg_match函数

PHP的preg_match函数可以用来在一个字符串中查找符合正则表达式的子字符串。函数原型如下:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

其中,pattern参数为正则表达式,subject参数为要搜索的字符串,matches参数为存储匹配结果的数组,flags参数用于指定搜索选项,offset参数为起始搜索位置。

如果找到了符合正则表达式的子字符串,preg_match函数将返回1,否则返回0。

以下是一个例子:

$mystring = 'hello world';
$findme   = 'world';
if (preg_match("/$findme/i", $mystring)) {
    echo "字符串 '$findme' 在字符串 '$mystring' 中被发现";
} else {
    echo "抱歉,没有找到字符串。";
}

上述代码的输出结果为:
字符串 'world' 在字符串 'hello world' 中被发现

三、substr_count函数

PHP的substr_count函数可以用来计算一个字符串中另一个字符串出现的次数。函数原型如下:

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

其中,haystack参数为要搜索的字符串,needle参数为要查找的字符串,offset参数为起始搜索位置,length参数为要搜索的字符数。

substr_count函数返回的是子字符串在原字符串中出现的次数,如果子字符串没有出现,则返回0。

以下是一个例子:

$mystring = 'hello world';
$findme   = 'l';
echo substr_count($mystring, $findme);

上述代码的输出结果为:
3

四、stripos函数

PHP的stripos函数与strpos函数类似,不同的是它是不区分大小写的。函数原型如下:

int stripos ( string $haystack , string $needle [, int $offset = 0 ] )

其中,haystack参数为要搜索的字符串,needle参数为要查找的字符串,offset参数为起始搜索位置。

如果找到了要查找的字符串,stripos函数将返回它在原字符串中首次出现的位置(位置从0开始数)。如果没找到,则返回false。

以下是一个例子:

$mystring = 'Hello World';
$findme   = 'world';
$pos = stripos($mystring, $findme);
if ($pos !== false) {
    echo "字符串 '$findme' 在字符串 '$mystring' 中被发现

"; echo "它在字符串 $mystring 的位置是 $pos

"; } else { echo '抱歉,没有找到字符串。'; }

上述代码的输出结果为:
字符串 'world' 在字符串 'Hello World' 中被发现
它在字符串 Hello World 的位置是 6

五、stristr函数

PHP的stristr函数与stripos函数类似,不同的是它返回的是从第一次出现的位置开始到字符串末尾的所有字符。函数原型如下:

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

其中,haystack参数为要搜索的字符串,needle参数为要查找的字符串,before_needle参数用于指定返回的子字符串中是否包含needle字符串。

如果找到了要查找的字符串,stristr函数将返回它在原字符串中首次出现的位置开始到字符串末尾的所有字符。如果没找到,则返回false。

以下是一个例子:

$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e'); // 输出 EXAMPLE.com
echo stristr($email, 'e', true); // 输出 US

上述代码的输出结果为:
EXAMPLE.com
US