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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度