+ -
当前位置:首页 → 问答吧 → 自己写了个高亮的函数

自己写了个高亮的函数

时间:2008-11-14

来源:互联网

自己写了个高亮的函数!可以自定义关键字和函数!

[php]
<?php
function highLight($code) {
$config_file = 'config.xml';
$xml = simplexml_load_file("config.xml");
$code = str_replace('>', '>', $code);
$code = str_replace('<', '<', $code);
$code =  str_replace("\t", "    ", nl2br($code));

$k_color = $xml->keywords->attributes();
$k_color = $k_color['color'];
$code = preg_replace("/\"(.{1,})\"/", "<span style=\"color:green;\">\"$1\"</span>", $code);
$code = preg_replace("/([url=file://\\$[0-9a-zA-z_]{1,})/]\\$[0-9a-zA-z_]{1,})/[/url]", "<span style=\"color:#80f;\">$1</span>", $code);
$code = preg_replace("/class\s{1,}([0-9a-zA-Z_]{1,})/", "class <span style=\"text-decoration:underline;\">$1</span>", $code);
foreach($xml->keywords->e as $e) {
  $code = preg_replace("/(\s{0,}$e\s{1,})/", '<span style="color:'. $k_color .";\">\$1</span>", $code);
}
unset($e);

$f_color = $xml->functions->attributes();
$f_color = $f_color['color'];
foreach($xml->functions->e as $e) {
  $code = str_replace($e, '<span style="color:'. $f_color .';">' . $e . '</span>', $code);
}
unset($e);
echo $code;
}
$code = <<<CODE
<?php
class MyClass {
private \$name;
private function sayHello() {
  echo "hello world";
}
public function __construct(\$name) {
  \$this->name = \$name;
}
}
function hide() {
global \$f;
echo \$f;
}
?>
CODE;
highLight($code);
?>

[/php][code]
config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<elements>
<keywords color="red">
  <e>private</e>
  <e>public</e>
  <e>var</e>
  <e>for</e>
  <e>foreach</e>
  <e>if</e>
  <e>else</e>
  <e>elseif</e>
  <e>while</e>
  <e>do</e>
  <e>until</e>
  <e>switch</e>
  <e>case</e>
  <e>break</e>
  <e>function</e>
  <e>class</e>
  <e>continue</e>
  <e>as</e>
  <e>global</e>
</keywords>
<functions color="blue">
  <e>abs</e>
  <e>echo</e>
  <e>print</e>
  <e>print_r</e>
  <e>mysql_connect</e>
</functions>
</elements>
[/code]

下载 (16.99 KB)
2008-11-14 17:26


作者: liexusong   发布时间: 2008-11-14

赞一个

作者: 0hudu   发布时间: 2008-11-14

不过还是 代码加亮SyntaxHighlighter好

作者: ieliwb   发布时间: 2008-11-25

顶起!

作者: ieliwb   发布时间: 2008-11-25

作者: sejie10011   发布时间: 2008-11-26

不错的说。

作者: ieliwb   发布时间: 2008-11-27

不错,赞!

作者: anyforever   发布时间: 2008-11-27