1

这是我写的代码

<?php 
            $response = file_get_contents('like.json');
            $arr =json_decode($response);
            foreach($arr->likes->data as $category){
                $findme    = $category->name;
                $search = 'Lets play Cricket today, what do you say about playing Bangladesh cricket CHI?';
                $pos2 = stripos($search, $findme);
                if ($pos2 !== false) {
                    $search = str_ireplace ( $findme , '<b>'.$findme.'</b>' , $search );
                    echo $search;               
                }       
        }

?>

在这里,我得到 $category->name 中的字符串数组,例如孟加拉国、板球、CHI、Sport ...。现在,在我的 $search 字符串中,我有一个小段落,例如,我想替换与$category->name 数组。但问题是如果它得到多次替换,那么它会打印出很多次。

我不知道如何解决它,应该很容易但无法正确解决。

4

2 回答 2

3

$search在循环外声明和输出变量。:

$response = file_get_contents('like.json');
            $arr =json_decode($response);
$search = 'Lets play Cricket today, what do you say about playing Bangladesh cricket CHI?';

foreach($arr->likes->data as $category){
   $findme    = $category->name;
   $pos2 = stripos($search, $findme);
   if ($pos2 !== false) {
      $search = str_ireplace ( $findme , '<b>'.$findme.'</b>' , $search );            
   }       
}

echo $search;
于 2013-03-25T07:35:19.390 回答
2

如果要替换搜索字符串中的所有类别名称,请先替换它们,然后以这种方式回显搜索字符串:

$response = file_get_contents('like.json');
$arr =json_decode($response);
$search = "Lets play Cricket today, what do"
         ." you say about playing Bangladesh cricket CHI?";
foreach($arr->likes->data as $category){
    $findme    = $category->name;
    $pos2 = stripos($search, $findme);
    if ($pos2 !== false) {
        $search = str_ireplace ( $findme , '<b>'.$findme.'</b>' , $search );
    }
}     
echo $search;               
于 2013-03-25T07:35:16.237 回答