How to color HTML elements based on user command line

When you enter something like "red: Hi:", it will print "Hello" in red. The following script doesn't work, and I don't know why (the one who created the PHP sort function is Graphain, thanks again!)

<?php 
  function getit($raw)
  {
  # If the value was posted
  $raw = isset($raw) ? $raw : "";
  # Split it based on ':'
  $parsed = explode(':', $raw);

  $colorClass = "";
  $text = "";

  if (count($parsed) >= 2)
  {
    $colorClass = $parsed[0];
    $text = $parsed[1];
    $text = "~~~" . $text . "~~~" . $colorClass;
    return $text;
  }
  }
?>

<script type="text/javascript">
function postit()
{
    var preview = document.getElementById("preview").value;
    var submit = document.getElementById("post").value;
    var text = <?php getit(submit); ?>
    var t = text[0];
    preview = t;
}
</script>

<textarea id="preview" cols=70 rows=5 readonly>Preview box</textarea>
<p>
<textarea id="post" cols=70 rows=5/>Submit box</textarea>
<p>
<input type="button" onclick="postit();" value="Submit"/>
+3
source share
2 answers
var text = <?php getit(submit); ?>

It seems you are mixing javascript and php.

in your javascript function that you are trying to pass into a value pulled out by javascript and placed in a php function.

php starts when the page is displayed in the browser, and javascript starts when the user clicks the button.

So, moving everything to javascript, I would do something like:

<script type="text/javascript">
function postit()
{
    var submit = document.getElementById("post").value;
    var newHTML = submit.replace(/\b(\w+):(\w+)\b/,'<span style="color: $1">$2</span>');

    document.getElementById("preview").innerHTML = newHTML;
}
</script>

<div id="preview" style="height: 120px; width: 500px; border: 1px solid grey;">Preview box</div>
<p>
<textarea id="post" cols=70 rows=5/>Submit box - test red:hi</textarea>
<p>
<input type="button" onclick="postit();" value="Submit"/>
+2

, - :

function getit($raw) {
    $t = preg_replace("/\\b([a-z]+):(\\S+)/",
        '<span style="color: $1">$2</span>', $raw);
    return json_encode($t);
}

echo getit("This is some red:example text");

:

"This is some <span style=\"color: red\">example<\/span> text"

, , , preg_replace_callback.

0

Source: https://habr.com/ru/post/1749523/


All Articles