Php 计算字符串中匹配的字数

Php 计算字符串中匹配的字数,php,Php,我有两条线。两者看起来很相似,但其中一个是主字符串,另一个是Finde字符串 例如: $MainString = 'Yellow Green Orange Blue Yellow Black White Purple'; $FinderString = 'Yellow Blue White'; 我现在的问题是如何将这些字符串拆分成一个数组,以便用另一个字符串中的另一个来检查每个字符串 这是我的密码: <?php $MainString = 'Yellow Green Orang

我有两条线。两者看起来很相似,但其中一个是主字符串,另一个是Finde字符串

例如:

 $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: 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首先,来吧

在这种情况下,可以将字符串拆分/分解为单独的数组,以单独检查颜色

为此,您可以使用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
?>


您可以先分解指针,然后在循环中使用每个分解的部分,然后只应用子字符串计数功能。一个简单的计数器和
+=
应该suffice@Ghost比我早几秒钟xDsee ups抱歉@DevsiOdedra堆栈溢出没有向我显示这一点我不知道为什么。。。抱歉被愚弄了…您可以使用此答案应用您当前的代码。请尝试<代码>代码$MainString=explode(“,$MainString”)<代码>代码$FinderString=explode(“,$FinderString”)<代码>代码echo$containsSearch=count(数组相交($FinderString,$MainString))@BhaveshPatel您的代码正在计算数组索引数。对于他的期望值,您应该在计数函数的末尾设置
+1
。)
<?php
   $colors = "Yellow Green Orange Blue Yellow Black White Purple";
   $colors = explode(" ", $colors);
   echo $colors[0]; // color 1
   echo $colors[1]; // color 2
?>