我要做的是创建一个语法高亮显示器。我需要帮助的是创建reg表达式来查找和突出显示punction标记,但我希望匹配排除某些字符之间的字符串“”,''并排除字符串已被评论或定义//,/ ** /,#。我目前正在使用这种模式
'/(!|%|\^|\*|\(|\)|\+|\=|\-|>|<|\?|,|\.|\:|\;|\'|&|\[|\]|\}|\{|~)(?=[^>]*(<|$))/'
这部分似乎可以解决标签之间的问题,但老实说它看起来不正确,我对如何正确构建模式毫无头绪。
(?=[^>]*(<|$))
这是我的精彩集锦课程
class SyntaxHighlight
{
public static function process($s,$lang,$raw = false)
{
$orig_s = $s;
$regexp = array(
//Keywords working
'/(?<!\w|\$|\%|\@|>)(and|or|xor|for|do|while|foreach|as|return|die|exit|if|then|else|
elseif|new|delete|try|throw|catch|finally|class|function|string|
array|object|resource|var|bool|boolean|int|integer|float|double|
real|string|array|global|const|static|public|private|protected|
published|extends|switch|true|false|null|void|this|self|struct|
char|signed|unsigned|short|long|break|goto|static_cast|const_cast|
LIMIT|ASC|DESC|ORDER|BY|SELECT|FROM|WHERE)(?!\w|=")/iux'
=> '<span class="K">$1</span>',
//$var, %var, @var
'/(?<!\w)(
(\$|\%|\@)(\->|\w)+
)(?!\w)/ix'
=> '<span class="V">$1</span>',
// Numbers (also look for Hex)
'/(?<!\w)(
0x[\da-f]+|
\d+
)(?!\w)(?=[^"]*(<|"))/ix'
=> '<span class="N">$1</span>',
//comments
'/(\/\*.*?\*\/|
\/\/.*?\n|
\#.[^a-zA-Z0-9]+?\|
\<\!\-\-[\s\S]+\-\-\>|
(?<!\\\)\'(.*?)(?<!\\\)\'
)/isx'
=> '<span class="C">$1</span>',
//char strings
'/\'(.+?)\'(?=[^>]*(<|$))/'
=> "<span class='CS'>'$1'</span>",
//back quote strings
'/\`(.+?)\`(?=[^>]*(<|$))/'
=> "<span class='BS'>`$1`</span>",
//strings
'/"(.+?)"(?=[^>]*(<|$))/'
=> '<span class="S">"$1"</span>',
//Punc
'/(!|%|\^|\*|\(|\)|\+|\=|\-|>|<|\?|,|\.|\:|\;|\'|&|\[|\]|\}|\{|~)(?=[^>]*(<|$))/'
=> '<span class="P">$1</span>',
);
$s = preg_replace( array_keys($regexp), array_values($regexp), $s);
if($lang == "Text" || $lang == "Other")
$s = $orig_s;
if($raw == "false")
$s = self::DisplayLineCount($s);
return '<pre style = "background-color:white;margin:0auto;text-align:left;overflow:auto;">'.$s.'</pre>';
}
private static function DisplayLineCount($s)
{
$i=1;
$count = substr_count($s, "\n");
$s = "<span style = 'color:#dfecf2;'>".$i."\t</span>".$s;
while($i <= $count)
{
++$i;
$s = preg_replace("/[\n]/","<span style = 'color:#dfecf2;'>".$i."\t</span>",$s,1);
}
return $s;
}
}
我从数据库获取高亮度的语法并调用这样的函数。
if(isset($row['syntax']) && $row['syntax'] == $cat_ && isset($row['title']) && $row['title'] == $top_ && isset($row['id']) && $row['id'] == $id_)
{
$id_ = isset($row['id']) ? $row['id'] : '';
$top_ = isset($row['title']) ? $row['title'] : '';
$top_ = htmlspecialchars($top_);
$auth_ = isset($row['author']) ? $row['author'] : '';
$date_ = isset($row['date']) ? $row['date'] : '';
$post_ = isset($row['paste']) ? $row['paste'] : '';
$newtext = htmlspecialchars($post_);
echo SyntaxHighlight::process($newtext,$cat_,$raw);
}
我是使用reg表达式模式的新手,所以请原谅我,并提前感谢你。