<?php
// 示例代码:检查字符串是否包含某个子字符串
// 方法一:使用strpos函数
$string = "Hello, welcome to the world of PHP!";
$substring = "PHP";
if (strpos($string, $substring) !== false) {
echo "字符串包含 '$substring'";
} else {
echo "字符串不包含 '$substring'";
}
// 方法二:使用stripos函数(忽略大小写)
$string = "Hello, welcome to the world of php!";
$substring = "PHP";
if (stripos($string, $substring) !== false) {
echo "字符串包含 '$substring'(忽略大小写)";
} else {
echo "字符串不包含 '$substring'(忽略大小写)";
}
// 方法三:使用strstr函数
$string = "Hello, welcome to the world of PHP!";
$substring = "PHP";
if (strstr($string, $substring) !== false) {
echo "字符串包含 '$substring'";
} else {
echo "字符串不包含 '$substring'";
}
?>
strpos 函数:用于查找子字符串在主字符串中第一次出现的位置。如果找到,则返回位置索引(从0开始),否则返回 false。注意,strpos 是区分大小写的。stripos 函数:与 strpos 类似,但忽略大小写。strstr 函数:用于查找子字符串在主字符串中的首次出现,并返回从该位置到字符串末尾的所有字符。如果没有找到,则返回 false。以上三种方法都可以用来检查一个字符串是否包含另一个子字符串,根据需求选择合适的方法即可。
下一篇:php exit
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站