1

here is the code I have written

<?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;               
                }       
        }

?>

here, I am getting array of string in $category->name like Bangladesh, Cricket, CHI, Sport .... Now in my $search string I have a small paragraph for instance, I want to replace any word that matches from the $category->name array. but problem is if it gets multiple replaces then it printing out that many times.

I dont know how to solve it, should be easy but cannot get it right.

2
  • Did you see regular expressions (regex) ? Commented Mar 25, 2013 at 7:33
  • regular expression as in ? Commented Mar 25, 2013 at 7:35

2 Answers 2

3

Declare and output variable $searchoutside the loop.:

$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;
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to replace all category names in search string first replace them then echo the search string this way:

$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;               

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.