- // Example use: $ spanned = codeWords ($ string_containing_keywords );
- // My site: andrew. dx. am
- // Using color = 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". $ value ."";
- }
- 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', 'wait', 'with ');
- $ Keywords2 = $ keywords;
- Array_walk ($ keywords, 'onlywholeword ');
- Array_walk ($ keywords2, 'addspan ', 'blue ');
- $ Code = preg_replace ($ keywords, $ keywords2, $ code );
- Return $ code;
- }
II. php automatically adds a keyword link to the article
Php function code that automatically adds a keyword link to the article.
Code:
-
$ Link = array (
- Baidu, http://www.baidu.com /',
- 'Php tutorial, http://bbs.it-home.org/wb/php /',
- 'Script School, http://bbs.it-home.org /',
- );
- $ Str = 'Search for php tutorials in Baidu to go to the php programming article provided by the programmer's house.
- The content to be replaced is placed here. ';
- $ Out = keylink ($ str, $ link, 1); // $ str original character $ link, replacing the link array, 3 replace times
- Echo $ out;
- Function _ sortDesc ($ a, $ B ){
- Return (strlen ($ a [0]) <strlen ($ B [0])? 1:-1;
- }
- Function keylink ($ str, $ link, $ count = 1)
- {
- $ LinkDefs = $ link;
- $ LinkMap = array ();
- Foreach ($ linkDefs as $ row ){
- $ LinkMap [] = explode (',', $ row );
- }
-
Foreach ($ linkMap as $ row ){
- $ Str = preg_replace ('/(\ s *)('. $ row [0]. ') (\ s * <\/a>)/sui',' $ {2} ', $ str );
- }
-
Usort ($ linkMap, '_ sortDesc ');
-
$ TmpKwds = array ();
-
Foreach ($ linkMap as $ I =>$ row ){
- List ($ kwd, $ url) = $ row;
- For ($ j = $ I + 1; $ j $ SubKwd = $ linkMap [$ j] [0];
- // If other keywords are included, replace them with other strings.
- If (strpos ($ kwd, $ subKwd )! = False ){
- $ TmpKwd = '{'. md5 ($ subKwd ).'}';
- $ Kwd = str_replace ($ subKwd, $ tmpKwd, $ kwd );
- $ TmpKwds [$ tmpKwd] = $ subKwd;
- }
- }
- // Replace text with link
- $ Str = preg_replace ('/('. $ row [0]. ')/sui','. $ kwd. '', $ str, $ count );
- }
-
// Replace the string that replaces the subkeyword
- Foreach ($ tmpKwds as $ tmp => $ kwd ){
- $ Str = str_replace ($ tmp, $ kwd, $ str );
- }
- Return $ str;
- }
- ?>
|