PHP 8 – 使用 str_contains() 检查字符串是否包含子字符串
在 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP