我目前在这里面临一个问题,我有很多不同的字符串:
"he#00ff00llo"
"#cc9200test"
等等。
我在HTML页面上输出这个内容(通过我的数据库抓取它) 无论如何,我想要实现的是读取#00ff00并将其作为颜色本身输出。
修改
这些是用户名,大部分时间都是这样的:#ff0000#SomeName |然后我想变成<span style="color: #ff0000">#SomeName</span>
哦,并且有几个颜色代码的用户名。
修改
我的朋友给了我这个代码,解决了我的问题。 :)
用PHP解决了这个问题
以下代码(由Oriol发布)正在运作! :)
本代码作品(PHP):
<?php
function colorCodesRenderProperly($name)
{
$name = htmlspecialchars($name);
if(preg_match('/^(#[0-9a-fA-F]{6})+$/', $name) === 1)
{
return $name;
}
preg_match_all('/#[0-9a-fA-F]{6}/', $name, $codes);
$replaced = array();
$codes_original = $codes;
$i = 0;
$count = 1;
foreach($codes[0] as &$code)
{
if(in_array($codes_original[0][$i], $replaced))
{
continue;
}
$code = sprintf('%02s', dechex((hexdec($code[1].$code[2])/255*128)))
.sprintf('%02s', dechex((hexdec($code[3].$code[4])/255*128)))
.sprintf('%02s', dechex((hexdec($code[5].$code[6])/255*128)));
$name = str_replace($codes_original[0][$i], "<span style=\"color: #$code;\">", $name, $count);
$replaced[] = $codes_original[0][$i];
$i++;
$count = 1;
}
while($i > 0)
{
$name .= "</span>";
$i--;
}
return $name;
}
?>
答案 0 :(得分:1)
试试这个:
var txt = document.createTextNode("he#00ff00llo"),
wrapper = document.createElement('span'),
regExp = /#[\da-f]{6}/i,
pos;
wrapper.appendChild(txt);
while(~(pos = txt.nodeValue.search(regExp))) {
txt = txt.splitText(pos);
var span = wrapper.cloneNode(false);
span.style.color = txt.nodeValue.substr(0,7);
txt.nodeValue = txt.nodeValue.substr(7);
span.appendChild(txt);
wrapper.appendChild(span);
}
// append wrapper to the DOM