PHP substr_count() 函数
PHP 教程
· 2019-01-30 13:57:20
实例
计算 "world" 在字符串中出现的次数:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
echo substr_count("Hello world. The world is nice","world");
?>
substr_count() 函数计算子串在字符串中出现的次数。
注释:子串是区分大小写的。
注释:该函数不计数重叠的子串(参见实例 2) 。
注释:如果 start 参数加上 length 参数大于字符串长度,该函数则生成一个警告(参见实例 3)。
语法
substr_count(string,substring,start,length)
| 参数 | 描述 |
|---|---|
| string | 必需。规定要检查的字符串。 |
| substring | 必需。规定要检索的字符串。 |
| start | 可选。规定在字符串中何处开始搜索。 |
| length | 可选。规定搜索的长度。 |
技术细节
| 返回值: | 返回子串在字符串中出现的次数。 |
|---|---|
| PHP 版本: | 4+ |
| 更新日志: | 在 PHP 5.1 中,新增了 start 和 length 参数。 |
更多实例
实例 1
使用所有的参数:
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
实例 2
重叠的子串:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
实例 3
如果 start 和 length 参数超过字符串长度,该函数则输出一个警告:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
由于长度值超过字符串的长度(3 + 9大于12)。所以这将输出一个警告。
点击查看所有 PHP 教程 文章: https://codercto.com/courses/l/5.html
数据资本时代
Viktor Mayer-Schnberger / 李晓霞、周涛 / 中信出版集团股份有限公司 / 2018-11-1 / CNY 58.00
【编辑推荐】 大数据除了能对我们的生活、工作、思维产生重大变革外,还能够做什么?畅销书《大数据时代》作者舍恩伯格在新书《数据资本时代》中,展示了大数据将如何从根本上改变经济——这并不是因为数据是一种新型石油,而是因为数据是一种新型润滑脂,它将给市场带来巨大能量,给公司带来巨大压力,使金融资本的作用大大削弱。赢家是市场,而并非资本。 这本书在当下国内出版,可以说恰逢其时。时下,中国经济正......一起来看看 《数据资本时代》 这本书的介绍吧!