PHP中判断字符串是否包含指定字符串的多种方法

分类:知识百科 日期: 点击:0

PHP中判断字符串是否包含指定字符串有多种方法,下面介绍几种常用的方法:

1、strpos()函数

strpos()函数是PHP中最常用的判断字符串是否包含指定字符串的方法,该函数用于查找字符串在另一个字符串中第一次出现的位置,如果查找到,则返回字符串的位置,如果没有查找到,则返回false。使用方法如下:

$str = 'this is a string';
$findme = 'string';
$pos = strpos($str, $findme);
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$str'";
} else {
    echo "The string '$findme' was found in the string '$str'";
    echo " and exists at position $pos";
}

2、strstr()函数

strstr()函数也可以用来判断字符串是否包含指定字符串,该函数用于查找字符串在另一个字符串中第一次出现的位置,如果查找到,则返回从该位置到字符串结尾的所有字符,如果没有查找到,则返回false。使用方法如下:

$str = 'this is a string';
$findme = 'string';
$pos = strstr($str, $findme);
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$str'";
} else {
    echo "The string '$findme' was found in the string '$str'";
    echo " and exists at position $pos";
}

3、preg_match()函数

preg_match()函数也可以用来判断字符串是否包含指定字符串,该函数用于检测一个字符串是否匹配另一个字符串,如果匹配则返回1,否则返回0。使用方法如下:

$str = 'this is a string';
$findme = 'string';
if (preg_match("/$findme/", $str)) {
    echo "The string '$findme' was found in the string '$str'";
} else {
    echo "The string '$findme' was not found in the string '$str'";
}

4、str_replace()函数

str_replace()函数也可以用来判断字符串是否包含指定字符串,该函数用于替换字符串中的指定字符串,如果替换成功,则返回替换后的字符串,如果没有替换成功,则返回false。使用方法如下:

$str = 'this is a string';
$findme = 'string';
$pos = str_replace($findme, '', $str);
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$str'";
} else {
    echo "The string '$findme' was found in the string '$str'";
    echo " and exists at position $pos";
}

以上就是,可以根据自己的实际需要选择合适的方法。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。