【问题标题】:php finding similar phrasesphp查找相似的短语
【发布时间】:2011-12-21 20:03:12
【问题描述】:

我正在尝试在 php 中编写一个脚本,该脚本在两段文本中找到相似的短语。我问过这个Question

  1. the cat is on the roof
  2. a man is on the stage

  A1 = [the, cat, is, on, the, roof]
  A2 = [a, man, is, on, the, stage]

  [the]: no match
  [cat]: no match
  [is]: match
  [is, on]: match
  [is, on, the]: match
  [is, on, the, roof]: no match
  [on]: match
  [on, the]: match
  [on, the, roof]: no match
  [the]: match
  [the, roof]: no match
  [roof]: no match
  -end-

我的代码如下。

<?php

echo match(explode(' ',$text1), explode(' ',$text2));

function match($old, $new){
$arr;
    foreach($old as $key=>$oldword) {   
        foreach($new as $key2=>$newword) {

            if($old[$key] == $new[$key2]) { 
                array_push($arr,$old[$key]);
                echo '<span style="color:red;">'.$old[$key].' </span>';
                }
                else {
                    echo $old[$key].' ';
                }
        }
    }
}

我得到以下输出

为什么单词会重复?

【问题讨论】:

    标签: php string loops


    【解决方案1】:

    对于您当前的问题,答案是因为您使用了嵌套的 for 循环。对于另一个问题,答案实际上是完全正确的:)。

    【讨论】:

      【解决方案2】:

      这是因为新数组的 foreach 循环正在为旧数组的循环的每次迭代运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-29
        • 2022-06-15
        • 2015-02-28
        • 2012-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多