public static function codeSnippet($file, $focus, $range = 7, $style = ['lineHeight' => 20, 'fontSize' => 13])
{
$html = highlight_file($file, true);
if (!$html) {
return false;
}
// 分割html保存到数组
$html = explode('<br />', $html);
$lineNums = count($html);
// 代码的html
$codeHtml = '';
// 获取相应范围起止索引
$start = $focus - $range < 1 ? 0 : $focus - $range - 1;
$end = $focus + $range > $lineNums ? $lineNums - 1 : $focus + $range - 1;
// 修正开始标签
// 有可能取到的片段缺少开始的span标签,而它包含代码着色的CSS属性
// 如果缺少,片段开始的代码则没有颜色了,所以需要把它找出来
if (substr($html[$start], 0, 5) !== '<span') {
while ($start - 1 >= 0) {
$match = [];
preg_match('/<span style="color: #([\\w]+)"(.(?!<\\/span>))+$/', $html[--$start], $match);
if (!empty($match)) {
$html[$start] = "<span style=\"color: #{$match[1]}\">" . $html[$start];
break;
}
}
}
for ($line = $start; $line <= $end; $line++) {
// 在行号前填充0
$index_pad = str_pad($line + 1, strlen($end), 0, STR_PAD_LEFT);
$line + 1 == $focus && ($codeHtml .= "<p style='height: " . $style['lineHeight'] . "px; width: 100%; _width: 95%; background-color: red; opacity: 0.4; filter:alpha(opacity=40); font-size:15px; font-weight: bold;'>");
$codeHtml .= "<span style='margin-right: 10px;line-height: " . $style['lineHeight'] . "px; color: #807E7E;'>{$index_pad}</span>{$html[$line]}";
$codeHtml .= $line + 1 == $focus ? '</p>' : ($line != $end ? '<br />' : '');
}
// 修正结束标签
if (substr($codeHtml, -7) !== '</span>') {
$codeHtml .= '</span>';
}
return <<<EOT
<div style="position: relative; font-size: {$style['fontSize']}px; background-color: #BAD89A;">
<div style="_width: 95%; line-height: {$style['lineHeight']}px; position: relative; z-index: 2; overflow: hidden; white-space:nowrap; text-overflow:ellipsis;">{$codeHtml}</div>
</div>
EOT;
}