PHP 中判断字符串包含的 10 种方法117
在 PHP 中判断字符串是否包含另一个字符串是一个常见的任务。有许多不同的方法可以执行此操作,每种方法都有其优点和缺点。
1. strpos()
strpos() 函数用于在字符串中查找另一个子串的第一次出现。如果找到子串,它将返回子串在字符串中开始的位置,否则返回 FALSE。```php
$string = 'Hello World';
$sub_string = 'World';
if (strpos($string, $sub_string) !== FALSE) {
echo '子串存在字符串中。';
}
```
2. stripos()
stripos() 函数与 strpos() 类似,但它是区分大小写的。这意味着它将忽略大小写差异,并返回子串在字符串中开始的位置,或者如果未找到,则返回 FALSE。```php
$string = 'Hello World';
$sub_string = 'WORLD';
if (stripos($string, $sub_string) !== FALSE) {
echo '子串存在字符串中。';
}
```
3. substr_count()
substr_count() 函数用于计算字符串中子串出现的次数。它返回子串在字符串中出现的次数,或者如果未找到,则返回 0。```php
$string = 'Hello World World';
$sub_string = 'World';
$count = substr_count($string, $sub_string);
echo '子串在字符串中出现 ' . $count . ' 次。';
```
4. strstr()
strstr() 函数用于在字符串中查找另一个子串的第一次出现,并返回从子串开始到字符串结尾的字符串部分。如果未找到子串,则返回 FALSE。```php
$string = 'Hello World';
$sub_string = 'World';
$result = strstr($string, $sub_string);
echo '从第一个匹配的位置开始的子串为:' . $result;
```
5. stristr()
stristr() 函数与 strstr() 类似,但它是区分大小写的。这意味着它将忽略大小写差异,并返回从子串开始到字符串结尾的字符串部分,或者如果未找到,则返回 FALSE。```php
$string = 'Hello WORLD';
$sub_string = 'world';
$result = stristr($string, $sub_string);
echo '从第一个匹配的位置开始的子串为:' . $result;
```
6. preg_match()
preg_match() 函数用于使用正则表达式在字符串中匹配子串。如果匹配成功,它将返回 1,否则返回 0。```php
$string = 'Hello World';
$sub_string = '/World/';
if (preg_match($sub_string, $string)) {
echo '子串存在字符串中。';
}
```
7. preg_match_all()
preg_match_all() 函数与 preg_match() 类似,但它返回所有匹配的子串的数组。如果没有任何匹配,它将返回一个空数组。```php
$string = 'Hello World World';
$sub_string = '/World/';
$matches = preg_match_all($sub_string, $string);
echo '匹配的子串为:';
print_r($matches);
```
8. in_array()
in_array() 函数用于检查一个值是否存在于数组中。它返回 TRUE 如果值存在,否则返回 FALSE。此方法可用于将字符串转换为数组,然后使用 in_array() 函数检查子串是否存在于数组中。```php
$string = 'Hello World';
$sub_string = 'World';
$array = str_split($string);
if (in_array($sub_string, $array)) {
echo '子串存在字符串中。';
}
```
9. explode()
explode() 函数用于将字符串拆分为数组,分隔符作为参数传递。此方法可用于将字符串拆分为子串数组,然后使用 in_array() 函数检查子串是否存在于数组中。```php
$string = 'Hello World';
$sub_string = 'World';
$array = explode(' ', $string);
if (in_array($sub_string, $array)) {
echo '子串存在字符串中。';
}
```
10. str_contains()
str_contains() 函数是 PHP 8 中引入的一个新函数。它用于检查字符串是否包含另一个子串。它返回 TRUE 如果子串存在,否则返回 FALSE。```php
$string = 'Hello World';
$sub_string = 'World';
if (str_contains($string, $sub_string)) {
echo '子串存在字符串中。';
}
```
2024-10-13
上一篇:PHP 文件操作:读写本地文件
Python与CAD数据交互:高效解析DXF与DWG文件的专业指南
https://www.shuihudhg.cn/132029.html
Java日常编程:掌握核心技术与最佳实践,构建高效健壮应用
https://www.shuihudhg.cn/132028.html
Python艺术编程:从代码到动漫角色的魅力之旅
https://www.shuihudhg.cn/132027.html
Python类方法调用深度解析:实例、类与静态方法的掌握
https://www.shuihudhg.cn/132026.html
Python 字符串到元组的全面指南:数据解析、转换与最佳实践
https://www.shuihudhg.cn/132025.html
热门文章
在 PHP 中有效获取关键词
https://www.shuihudhg.cn/19217.html
PHP 对象转换成数组的全面指南
https://www.shuihudhg.cn/75.html
PHP如何获取图片后缀
https://www.shuihudhg.cn/3070.html
将 PHP 字符串转换为整数
https://www.shuihudhg.cn/2852.html
PHP 连接数据库字符串:轻松建立数据库连接
https://www.shuihudhg.cn/1267.html