php - 计算字符串中匹配的单词数
问题描述
我有两个字符串。两者看起来相似,但其中一个是主字符串,另一个是查找字符串。
例如:
$MainString = 'Yellow Green Orange Blue Yellow Black White Purple';
$FinderString = 'Yellow Blue White';
我现在的问题是如何将这些字符串拆分为一个数组以将每个字符串与另一个字符串中的另一个进行检查?
这是我尝试过的代码:
<?php
$MainString = 'Yellow Green Orange Blue Yellow Black White Purple';
$FinderString = 'Yellow Blue White';
$resault = substr_count($MainString, $FinderString);
echo("number of matched colores: ".$resault);
?>
我的代码的结果:
number of matched colores: 0
我对本准则的期望:
number of matched colores: 4
有人可以帮我解决这个问题吗?
--- 帮助后的最终代码: ---
现在我写了这段代码,我猜这不是最好的,但他可以工作。
<?php
$MainString = 'Yellow Green Orange Blue Yellow Black White Purple';//declare the main String
$FinderString = 'Yellow Blue White'; //declare the finder String
$MainlyString = explode(" ",$MainString); //splitting the massive string into an Array.
$FindlyString = explode(" ",$FinderString); //splitting the massive string into an Array.
$resault = 0; //declare the counters
foreach($MainlyString as $main) { //running through the Array and give the result an Alias.
foreach($FindlyString as $find) { //runing through the Array and gave the resault an Alias.
if (substr_count($main, $find) == 1) { //Checking if a month is matching a mother.
$resault = $resault + 1; //increase the counter by one
}
}
}
echo("number of matched month: ".$resault."<br>"); //output of the counter
?>
谢谢你们的帮助。:)
解决方案
您好 PassCody 首先欢迎使用 Stackoverflow。
在这种情况下,您可以将字符串拆分/分解为一个单独的数组以单独检查颜色。
为此,您可以使用 PHP 函数 explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) 返回一个字符串数组,每个字符串都是通过在字符串形成的边界上拆分字符串而形成的子字符串分隔符。
这是一个例子:
<?php
$colors = "Yellow Green Orange Blue Yellow Black White Purple";
$colors = explode(" ", $colors);
echo $colors[0]; // color 1
echo $colors[1]; // color 2
?>
推荐阅读
- java - 是否可以让 SwaggerHub 生成没有“@schema”注释的客户端 sdk 模型(java)?
- spring - Spring 在 Kotlin 对象中自动装配是多余的吗?
- git - git - 查找创建分支的提交
- wildfly - Wildfly 找不到要注入 CDI 托管 bean 的持久性单元
- ios - 当应用程序完全关闭时,如何通过 APNS 传递推送通知?
- ios - 到达IOS的视频部分
- node.js - 错误:libnode.so.64:无法打开共享对象文件:没有这样的文件或目录 - Docker 容器
- mysql - 为什么加载环境变量主函数golang
- amazon-web-services - 将特定事件附加到 cloudwatch 事件规则
- sql - select into for of cursor 无法识别我的属性