php给一组指定关键词添加span标签的方法

这里是php给一组指定的关键词添加span标签,高亮突出显示关键词

// Example use: $spanned = codeWords($string_containing_keywords); // My site: andrew.dx.am // Using colour==blue, but different arrays of words and different // colours can be added. function onlyWholeWords(&$value, $key) { // Ignores words after // comment delimiters. //$value = "/\b(" . $value . ")\b/"; // doesn't handle comments //$value = "/^(?:(?!\/\/).)*\K\b(" . $value . ")\b/"; // \K lookbehind alternative is not supported in PHP < 5.2.4, so use: $value = "/^((?:(?!\/\/).)*)\b" . $value . "\b/"; } function addSpan(&$value, $key, $color='blue') { $value = "$1<span>" . $value . "</span>"; } function codeWords($code) { $keywords = array('as', 'break', 'case', 'class', 'continue', 'default', 'do', 'elif', 'else', 'elseif', 'for', 'foreach', 'function', 'if', 'new', 'null', 'return', 'self', 'switch', 'this', 'to', 'typeof', 'until', 'var', 'void', 'while', 'with'); $keywords2 = $keywords; array_walk($keywords, 'onlyWholeWords'); array_walk($keywords2, 'addSpan', 'blue'); $code = preg_replace($keywords, $keywords2, $code); return $code; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/d79bbfdcc2d0220e589b9e9b89292929.html