lyborko lyborko - 3 months ago 9
PHP Question

Is it possible to change original html text in php?

I am trying to make "manner friendly" website. We use different declination dependent on gender and other factors. For example:

You did = robili
It did = robilo
She did = robila


Linguisticaly this is very simplified (and unlucky) example! I would like to change html text in php file where appropriate. For example

<? php
something
?>

html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^</div>

<? php something ?>


Now I would like to replace all occurences of different tokens ^characters|characters|characters^ and replace them by one of their internal values according to "gender".

It is easy in javascript on the client side, but you will see all this weird "tokenizing" before javascript replace it.
Here I do not know the elegant solution.

Or do you have better idea?

Thanks for advice.

Answer

You can add these scripts before and after the HTML:

<?php

// start output buffering
ob_start();

?>
<html>
<body>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^, but also vital^si|sa|ste^, borko^mal|mala|malo^ </div>
</body>
</html>
<?php

$use  = 1; // indicate which declination to use (0,1 or 2)

// get buffered html
$html = ob_get_contents();
ob_end_clean();

// match anything between '^' than's not a control chr or '^', min 5 and max 20 chrs.
if (preg_match_all('/\^[^[:cntrl:]\^]{3,20}\^/',$html,$matches))
{
  // replace all
  foreach (array_unique($matches[0]) as $match)
  {
    $choices = explode('|',trim($match,'^'));
    $html    = str_replace($match,$choices[$use],$html);
  }
}

echo $html;

This returns:

html text of the page and somewhere is the word "robil" we tried to robilo, but also vitalsa, borkomala