0

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); 
user3857924
  • 86
  • 3
  • 15
  • You could always try to some combination of http://php.net/manual/en/function.html-entity-decode.php and http://php.net/manual/en/function.htmlentities.php –  Nov 05 '15 at 12:50
  • Possible duplicate of [RegEx with preg\_match to find and replace a SIMILAR string](http://stackoverflow.com/questions/33671497/regex-with-preg-match-to-find-and-replace-a-similar-string) – Madivad Nov 12 '15 at 14:56

2 Answers2

0

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); ?>;"
                               ^                                                    ^
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

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

Siddhartha esunuri
  • 1,104
  • 1
  • 17
  • 29