php - 字符串中匹配的PHP字数位置
问题描述
我试图找出一个字符串的位置出现在另一个字符串中的位置。
我可以使用 strpos 但这会返回字符位置,我正在寻找字数。例如:
$haystack = 'The letters PHP stand for PHP: Hypertext Preprocessor. PHP originally stood for. Personal Home Page Tools.';
$needle = 'PHP: Hypertext Preprocessor';
magic_function($haystack, $needle); // This should return 6
解决方案
你可以很简单地做到这一点,像这样:
<?php
function magic_function($haystack, $needle){
$strBeforeNeedle = substr($haystack, 0, strpos($haystack, $needle));
$wordCount = str_word_count($strBeforeNeedle);
return $wordCount;
}
$haystack = 'The letters PHP stand for PHP: Hypertext Preprocessor. PHP originally stood for. Personal Home Page Tools.';
$needle = 'PHP: Hypertext Preprocessor';
echo magic_function($haystack, $needle); // This should return 6
只需提取前面的字符串$needle
并计算单词。+1
如果您想要 中的第一个单词的数量,请添加 a $needle
,或者保持原样以获取其前面所有单词的数量。
推荐阅读
- android - wix react-native-navigation 更改选项卡动画
- python - 无法从 Django 视图返回响应到前端
- c# - 如何从动作创建 Observable
? - hibernate - ORA-01400: 当使用 @onetomany 映射并且在子端具有复合主键时,无法将 NULL 插入
- python-3.x - 在列表中删除 0 时跳过 False
- apache-kafka - Kafka K-SQL 数据类型
- excel - 更新工作表内容会导致其他工作表之间的链接中断
- asp.net-mvc - Viewbag 为每次迭代分配值导致错误
- angular - 无法导入“@angular/common/http”
- c# - c++ 和 C# 中的等效系统时钟毫秒数?