比较php中的两个字符串并添加标记

时间:2015-06-16 19:11:48

标签: php

我想匹配两个字符串,如果有任何单词匹配,我想为它们添加标记。

我尝试过类似下面的代码

$old = "one two three";

$new = "how is one related to two";

foreach (explode(" ", $old) as $str) {
    $str .= str_replace($str, "<b>$new</b>", $str);
}
echo trim($str);

已过滤结果how is <b>one</b> related to <b>two</b>

如果可能的话,请建议我使用其他方法。如果不可能,请告诉我循环。

5 个答案:

答案 0 :(得分:2)

记住:

str_replace( look_for_this , replace_it_wtih_this, look_through_this);

在您的代码中,您使用.=,这只会在每次迭代时复制一个新句子。我会这样做:

$old = "one two three";
$sentence = "how is one related to two";
$arr = explode(" ", $old);
foreach ($arr as $word) {
    $sentence = str_replace($word, "<b>$word</b>", $sentence);
}
echo trim($sentence);

结果:

how is <b>one</b> related to <b>two</b>

答案 1 :(得分:1)

这是一种方法,我认为错误是使用.=而不是=以及str_replace()PHP Sandbox)的一些混合参数

$searchwords = "one two three";

$string = "how is one related to two";

foreach (explode(" ", $searchwords) as $searchword) {
    $string = str_replace($searchword, "<b>{$searchword}</b>", $string);
}

echo trim($string);

答案 2 :(得分:0)

试试这个:

foreach(explode(" ",$old) as $lol)
{
    $new = str_replace($lol, "<b>".$lol."</b>", $new);
}

答案 3 :(得分:0)

尝试使用preg_replace而不是loop

<?php
$pattern = "/one|two|three/i";
$string = "how is one related to two";
$replacement = "<b>$0</b>";
$result = preg_replace($pattern, $replacement, $string);
echo $result;

结果将是

how is <b>one</b> related to <b>two</b>

您可以从here查看preg_replace。

答案 4 :(得分:0)

所有人的preg_replace:

function _replace($old,$new){
    $search = str_replace(' ',')|(',$old);
    return preg_replace("/($search)/i",'<b>$0</b>',$new);
}
echo _replace("one two three","how is one related to two");