PHP 8 – 使用 str_contains() 检查字符串是否包含子字符串
phpserver side programmingprogramming更新于 2025/8/5 3:22:17
在 PHP 8 中,str_contains 函数用于判断字符串是否在任意位置包含指定的子字符串。str_contains 函数用于检查第一个字符串是否包含在第二个字符串中,并根据是否找到该字符串返回 true / false 布尔值。该函数含义不言自明。
str_contains(string $haystack, string $needle): bool
示例 1:PHP 8 str_contains 函数。
<?php
if (str_contains('great reading tutorial', 'tutorial')) {
var_dump('Tutorial has been found');
}
?>
输出
string(23) "Tutorial has been found"
示例:str_contains 函数。
<?php
if (str_contains('great reading tutorial', 'hello')){
var_dump('great reading');
}
?>
注意: 上述程序返回 false,因为第一个字符串不包含第二个字符串。
strpos() 函数
在 PHP 7.x 中,strops() 函数用于检查给定字符串是否包含另一个字符串。此函数返回字符串needle的位置,如果未找到字符串needle,则返回false。
if (strpos('string with lots of words', 'words') !== false) { /* … */}
示例:PHP 7.x strops() 函数
<?php
$string = 'Hello World!';
if (strpos($string, 'Hello') !== false) {
echo 'True';
}
?>
输出
True

