简体   繁体   中英

php finding similar phrases

I am trying to program a script in php which finds similar phrases in two pieces of text. Which I have asked this 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-

My Code is below.

<?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].' ';
                }
        }
    }
}

I get the following output

在此输入图像描述

Why are the words repeating?

For your current question, the answer is that it's because you use a nested for-loop. For the other question, the answer is quite right actually :).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM