当您输入“red:Hi:”之类的内容时,它会以红色键入“Hi”。 以下脚本不起作用,我不知道为什么,(制作PHP函数的人是Graphain,再次感谢!)
<?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"/>
答案 0 :(得分:2)
var text = <?php getit(submit); ?>
你似乎在混合javascript和php。
在你的javascript函数中,你试图传递一个由javascript取出的值并将其放入php函数。
当页面输出到浏览器时运行php,而当用户点击按钮时运行javascript。所以将所有内容移动到javascript,我会做类似的事情:
<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"/>
答案 1 :(得分:0)
也许是这样的事情:
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
代替。