Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php字符串包含某个字符串

作者:洃铯哖輪   发布日期:2025-10-16   浏览:57

<?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'";
}
?>

解释说明:

  1. strpos 函数:用于查找子字符串在主字符串中首次出现的位置。如果找到,返回位置索引;如果没有找到,返回 false。注意:!== false 是为了避免将位置 0 误判为未找到。
  2. strstr 函数:用于查找子字符串首次出现的位置,并返回从该位置到字符串末尾的部分。如果未找到,返回 false
  3. str_contains 函数(PHP 8.0+):直接返回布尔值,表示子字符串是否存在于主字符串中。这是最简洁的方法,但仅适用于 PHP 8.0 及以上版本。

选择适合你 PHP 版本和需求的方法即可。

上一篇:php时间戳

下一篇:php while

大家都在看

php session用法

php 定义常量

phpisset函数

php html转图片

php后端

php爬虫框架

php读取csv文件

php+mysql动态网站开发

php 三元表达式

php文件加密

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站