duannaxin9975 2019-08-02 07:27
浏览 255
已采纳

计算字符串中匹配的单词数量[重复]

This question already has an answer here:

I have two Strings. Both seems similar but one of them is the main String and the other is the Finde String.

For Example:

 $MainString = 'Yellow Green Orange Blue Yellow Black White Purple';
 $FinderString = 'Yellow Blue White';

My Question now is how to split those Strings in to an Array to check each one with the other one of the other string?

Here is my Tryed code:

<?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);
?>

Resault of my Code:

number of matched colores: 0

My expection of this Code:

number of matched colores: 4

Can some one pleas help me to fix this?

--- FINAL CODE AFTER HELP: ---

Now I wrote this code it's not the best I guess but he works.

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

Thanks for the help guys. :)

</div>
  • 写回答

1条回答 默认 最新

  • duanhun3273 2019-08-02 07:30
    关注

    Hello PassCody first of all wellcome on Stackoverflow.

    In this case you can split/explode the String into a separate Array to single check the colores.

    For this you can use the PHP function explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

    Here is an Example:

    <?php
       $colors = "Yellow Green Orange Blue Yellow Black White Purple";
       $colors = explode(" ", $colors);
       echo $colors[0]; // color 1
       echo $colors[1]; // color 2
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效