当前位置:Gxlcms > PHP教程 > php关键词自动添加span标签与关键词高亮代码

php关键词自动添加span标签与关键词高亮代码

时间:2021-07-01 10:21:17 帮助过:3人阅读

  1. // Example use: $spanned = codeWords($string_containing_keywords);
  2. // My site: andrew.dx.am
  3. // Using colour==blue, but different arrays of words and different
  4. // colours can be added.
  5. function onlyWholeWords(&$value, $key) {
  6. // Ignores words after // comment delimiters.
  7. //$value = "/\b(" . $value . ")\b/"; // doesn't handle comments
  8. //$value = "/^(?:(?!\/\/).)*\K\b(" . $value . ")\b/";
  9. // \K lookbehind alternative is not supported in PHP < 5.2.4, so use:
  10. $value = "/^((?:(?!\/\/).)*)\b" . $value . "\b/";
  11. }
  12. function addSpan(&$value, $key, $color='blue') {
  13. $value = "$1" . $value . "";
  14. }
  15. function codeWords($code) {
  16. $keywords = array('as', 'break', 'case', 'class',
  17. 'continue', 'default', 'do', 'elif', 'else',
  18. 'elseif', 'for', 'foreach', 'function', 'if',
  19. 'new', 'null', 'return', 'self', 'switch',
  20. 'this', 'to', 'typeof', 'until',
  21. 'var', 'void', 'while', 'with');
  22. $keywords2 = $keywords;
  23. array_walk($keywords, 'onlyWholeWords');
  24. array_walk($keywords2, 'addSpan', 'blue');
  25. $code = preg_replace($keywords, $keywords2, $code);
  26. return $code;
  27. }

二、php自动给文章加关键词链接

自动给文章加关键词链接的php函数代码。

代码:

  1. $link = array(

  2. '百度,http://www.baidu.com/',
  3. 'php教程,http://bbs.it-home.org/wb/php/',
  4. '脚本学堂,http://bbs.it-home.org/',
  5. );
  6. $str = '在百度中搜索php教程就可以到程序员之家提供的php编程文章
  7. 此处放置需要替换的内容。';
  8. $out=keylink($str,$link,1); //$str 原始字符 $link,替换链接数组, 3替换次数
  9. echo $out;
  10. function _sortDesc($a, $b) {
  11. return (strlen($a[0]) < strlen($b[0])) ? 1 : -1;
  12. }
  13. function keylink($str,$link,$count=1)
  14. {
  15. $linkDefs = $link;
  16. $linkMap = array();
  17. foreach($linkDefs as $row) {
  18. $linkMap[] = explode(',', $row);
  19. }

  20. foreach($linkMap as $row) {

  21. $str = preg_replace('/(\s*)('.$row[0].')(\s*<\/a>)/sui', '${2}', $str);
  22. }

  23. usort($linkMap, '_sortDesc');

  24. $tmpKwds = array();

  25. foreach($linkMap as $i=>$row) {

  26. list($kwd, $url) = $row;
  27. for($j=$i+1; $j$subKwd = $linkMap[$j][0];
  28. //如果包含其他关键字,暂时替换成其他字符串
  29. if(strpos($kwd, $subKwd) !== false) {
  30. $tmpKwd = '{'.md5($subKwd).'}';
  31. $kwd = str_replace($subKwd, $tmpKwd, $kwd);
  32. $tmpKwds[$tmpKwd] = $subKwd;
  33. }
  34. }
  35. //把文字替换成链接
  36. $str = preg_replace('/('.$row[0].')/sui', ''.$kwd.'', $str, $count);
  37. }

  38. //把代替子关键字的字符串替换回来

  39. foreach($tmpKwds as $tmp=>$kwd) {
  40. $str = str_replace($tmp, $kwd, $str);
  41. }
  42. return $str;
  43. }
  44. ?>

人气教程排行