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