21xrx.com
2025-03-25 12:01:11 Tuesday
文章检索 我的文章 写文章
PHP实现字符串包含操作示例
2023-06-14 09:25:51 深夜i     8     0
PHP 字符串包含 strpos strstr

在PHP中,我们可以使用“strpos”和“strstr”函数来实现字符串包含操作。这两个函数可以检查一个字符串是否包含另一个指定的字符串,并返回符合条件的位置或字符串本身。

下面的示例代码演示了如何使用这两个函数进行字符串包含操作。

$text = "I love PHP!";
$word = "PHP";
//使用“strpos”函数进行包含判断
if (strpos($text, $word) !== false) {
  echo "The text contains the word '$word'.";
} else {
  echo "The text does not contain the word '$word'.";
}
echo " ";
//使用“strstr”函数进行包含判断
if (strstr($text, $word)) {
  echo "The text contains the word '$word'.";
} else {
  echo "The text does not contain the word '$word'.";
}
?>

上述代码中,“$text”变量是一个字符串,它包含了“$word”变量中指定的字符串。在使用“strpos”函数和“strstr”函数进行包含判断后,根据函数返回值的不同进行相应的输出操作。

  
  

评论区