PHP

在php中,如何判断一个字符串是否包含另一个

小樊
83
2024-08-15 01:36:38
栏目: 编程语言

要判断一个字符串是否包含另一个字符串,可以使用PHP中的substr_count()函数或者strpos()函数。

  1. 使用substr_count()函数
$string1 = "Hello World";
$string2 = "World";

if (substr_count($string1, $string2) > 0) {
    echo "字符串包含在另一个字符串中";
} else {
    echo "字符串不包含在另一个字符串中";
}
  1. 使用strpos()函数
$string1 = "Hello World";
$string2 = "World";

if (strpos($string1, $string2) !== false) {
    echo "字符串包含在另一个字符串中";
} else {
    echo "字符串不包含在另一个字符串中";
}

以上代码中,substr_count()函数用于计算一个字符串在另一个字符串中出现的次数,如果大于0则说明字符串包含在另一个字符串中。strpos()函数用于查找一个字符串在另一个字符串中第一次出现的位置,如果返回的值不等于false则说明字符串包含在另一个字符串中。

0
看了该问题的人还看了