Skip to content
Advertisement

Changing some words in a string for highlight (PHP)

I can run JS Code smoothly but unfortunately, I could not do the same in PHP. I want to change some terms in the text for highlight. How can I do that?

 var words = 'word1#word2#word3';
    var string = 'hello world, this is a word1, word2 and word3';
    
    words.split("#").map(w => {
      var regex = new RegExp('\b' + w + '\b', 'gi');
      string = string.replace(regex, `<span class="highlight">${w}</span>`);
    });

    console.log(string);

PHP code:

$words = 'word1#word2#word3';
$string = "hello world, this is a word1, word2 and word3";
$parts = explode('#', $words);
preg_match_all('\b' + w + '\b', 'gi', $string, $parts);
$result = array_combine($parts[1], $parts[2]);

var_dump($result);

Advertisement

Answer

I used explode to create an array of patterns called $highlights, to match the words that it exploded by space too, then i do a loop foreach over a $words and check if it match any of highlights words by using in_array if so will highlight it by using span tag colored with red, otherwise it return it as it is.

<?php
$highlights = 'word1#word2#word3';
$pieces = explode('#', $highlights);

$sentence = "hello world, this sentence contains some word should be highlighted a word1 and word2 and word3";
$words = explode(' ', $sentence);

$highlighted = '';
foreach ($words as $word) {
    if(in_array($word, $pieces))
        $highlighted .= "<span style='color:red;'>$word</span> ";
    else
        $highlighted .= $word." ";
}

echo $highlighted;
?>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement