本文實例講述了php給一組指定關(guān)鍵詞添加span標簽的方法。分享給大家供大家參考。具體如下:
這里是php給一組指定的關(guān)鍵詞添加span標簽,高亮突出顯示關(guān)鍵詞
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// 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 style='color:$color'>" . $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 ; } |
希望本文所述對大家的php程序設計有所幫助。