PHP 检查字符串是否包含子字符串

2021/7/1 17:27:56

本文主要是介绍PHP 检查字符串是否包含子字符串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

字符串是一个字符序列,它既可以用作文字常量,也可以用作某种变量。字符串的特定部分称为子字符串。

PHP 提供strpos()了检查字符串是否包含特定子字符串的函数。strpos() 函数返回子字符串在字符串中第一次出现的位置。如果未找到子字符串,则返回 false 作为输出。

本教程为您提供了三个示例来检查字符串是否包含子字符串。您还可以检查子字符串是否位于主字符串的开头。

str_contains

(PHP 8)

str_contains — Determine if a string contains a given substring

说明

str_contains(string $haystack, string $needle): bool

Performs a case-sensitive check indicating if needle is contained in haystack.

参数

haystack

The string to search in.

needle

The substring to search for in the haystack.

返回值

Returns true if needle is in haystackfalse otherwise.

范例

示例 #1 Using the empty string ''

<?php
if (str_contains('abc', '')) {
    echo "Checking the existence of the empty string will always return true";
}
?>

--------------------------------------------------------------------

strpos

(PHP 4, PHP 5, PHP 7, PHP 8)

strpos — 查找字符串首次出现的位置

说明

strpos(string $haystack, mixed $needle, int $offset = 0): int

返回 needle 在 haystack 中首次出现的数字位置。

参数

haystack

在该字符串中进行查找。

needle

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。

返回值

返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从0开始,而不是从1开始的。

如果没找到 needle,将返回 false

警告

此函数可能返回布尔值 false,但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本说明
7.1.0开始支持负数的 offset

范例

示例 #1 使用 ===

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 'a' 是第 0 位置上的(第一个)字符。
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

示例 #2 使用 !==

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// 使用 !== 操作符。使用 != 不能像我们期待的那样工作,
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 false。
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>

示例 #3 使用位置偏移量

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>

注释

注意: 此函数可安全用于二进制对象。

结论

在本教程中,您学习了使用 PHP 编程语言检查字符串是否包含子字符串。



这篇关于PHP 检查字符串是否包含子字符串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程