<?php
// 示例代码:检查字符串是否包含某个子字符串
// 方法一:使用strpos函数
$string = "Hello, welcome to the world of PHP!";
$substring = "PHP";
if (strpos($string, $substring) !== false) {
echo "字符串包含 '$substring'";
} else {
echo "字符串不包含 '$substring'";
}
// 方法二:使用strstr函数
$string = "Hello, welcome to the world of PHP!";
$substring = "PHP";
if (strstr($string, $substring)) {
echo "字符串包含 '$substring'";
} else {
echo "字符串不包含 '$substring'";
}
// 方法三:使用str_contains函数(PHP 8.0+)
$string = "Hello, welcome to the world of PHP!";
$substring = "PHP";
if (str_contains($string, $substring)) {
echo "字符串包含 '$substring'";
} else {
echo "字符串不包含 '$substring'";
}
?>
strpos
函数:用于查找子字符串在主字符串中首次出现的位置。如果找到,返回位置索引;如果没有找到,返回 false
。注意:!== false
是为了避免将位置 0
误判为未找到。strstr
函数:用于查找子字符串首次出现的位置,并返回从该位置到字符串末尾的部分。如果未找到,返回 false
。str_contains
函数(PHP 8.0+):直接返回布尔值,表示子字符串是否存在于主字符串中。这是最简洁的方法,但仅适用于 PHP 8.0 及以上版本。选择适合你 PHP 版本和需求的方法即可。
上一篇:php时间戳
下一篇:php while
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站