字符串替换混合文本和HTML(客户端或服务器端)

I want to replace strings of text and html on a webpage. This is for the purpose of highlighting pieces of text. So, highlighted text is stored in a database, and when its webpage is loaded, the code should find and replace the piece of text.

For example,

$original_string = "SOME TEXT"; 
$replacement_string = "<span data-id='7334' class='highlight'>SOME TEXT</span>"; 

I had issues using PHP str_replace, as it wasn't very good with replacing weird html entities or larger strings.

So now, I am trying to do it on the client-side using JS, and have had much better results using js replace().

My question is - what is the best way to achieve the above goal? Should I use a PHP parser or stick with JS ?

And if I use JS, how should I structure the for loop so that all replacements are made on the same text? This did not quite work:

var value = $('#domainContainer').html();

    var $highlightsArray_search = <?php echo json_encode($highlightsArray_search); ?>;
    var $highlightsArray_replace = <?php echo json_encode($highlightsArray_replace); ?>;

    for(var i=0; i<2; i++){
        var search_value = $highlightsArray_search[i];
        var replace_value = $highlightsArray_replace[i];

        var formattedSnippet = value.replace(search_value, replace_value);

        value = formattedSnippet;

    }

    $('#domainContainer').html(formattedSnippet); 

You have to wrap php code with quotes .Just change like this,

var $highlightsArray_search = "<?php echo json_encode($highlightsArray_search); ?>;"
                              ^                                                    ^
var $highlightsArray_replace = "<?php echo json_encode($highlightsArray_replace); ?>;"
                               ^                                                    ^

Take your html code in to php string for example.

<?php
$original_string = "SOME TEXT"; 
$first ="<span data-id='7334' class='highlight'>";
$second = "</span>";
echo $first.$original_string.$second;
?>

Try this may be helpful