欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php自动给文章加关键词链接的实现代码

程序员文章站 2022-05-10 16:29:43
...
  1. /**
  2. * 添加文章关键词,内链
  3. * by bbs.it-home.org
  4. */
  5. $link = array(
  6. ‘百度,http://www.baidu.com/’,
  7. ‘dedecms,http://bbs.it-home.org/’,
  8. );
  9. $str = ‘在百度中搜索dedecms’;
  10. $out = keylink ( $str, $link, 1 );
  11. //$str 原始字符 $link,替换链接数组, 3替换次数
  12. echo $out;
  13. function _sortDesc($a, $b) {
  14. return (strlen ( $a [0] ) }
  15. function keylink($str, $link, $count = 1) {
  16. $linkDefs = $link;
  17. $linkMap = array ();
  18. foreach ( $linkDefs as $row ) {
  19. $linkMap [] = explode ( ‘,’, $row );
  20. }
  21. foreach ( $linkMap as $row ) {
  22. $str = preg_replace ( ‘/(s*)(‘ . $row [0] . ‘)(s*)/sui’, ‘${2}’, $str );
  23. }
  24. usort ( $linkMap, ‘_sortDesc’ );
  25. $tmpKwds = array ();
  26. foreach ( $linkMap as $i => $row )
  27. {
  28. list ( $kwd, $url ) = $row;
  29. for($j = $i + 1; $j {
  30. $subKwd = $linkMap [$j] [0];
  31. //如果包含其他关键字,暂时替换成其他字符串
  32. if (strpos ( $kwd, $subKwd ) !== false)
  33. {
  34. $tmpKwd = ‘{‘ . md5 ( $subKwd ) . ‘}’;
  35. $kwd = str_replace ( $subKwd, $tmpKwd, $kwd );
  36. $tmpKwds [$tmpKwd] = $subKwd;
  37. }
  38. }
  39. //把文字替换成链接
  40. $str = preg_replace ( ‘/(‘ . $row [0] . ‘)/sui’, ‘’ . $kwd . ‘’, $str, $count );
  41. }
  42. //把代替子关键字的字符串替换回来
  43. foreach ( $tmpKwds as $tmp => $kwd ) {
  44. $str = str_replace ( $tmp, $kwd, $str );
  45. }
  46. return $str;
  47. }
  48. ?>
复制代码