duannaxin9975 2019-08-01 23:27
浏览 256
已采纳

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

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-01 23: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
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部