首页 > 解决方案 > 计算字符串中匹配的单词数

问题描述

我有两个字符串。两者看起来相似,但其中一个是主字符串,另一个是查找字符串。

例如:

 $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
?>

谢谢你们的帮助。:)

标签: php

解决方案


您好 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
?>

推荐阅读