Implementation code for php to automatically add keyword links to articles

WBOY
Release: 2016-07-25 08:57:36
Original
1262 people have browsed it
  1. /**
  2. * Add article keywords and internal links
  3. * by bbs.it-home.org
  4. */
  5. $link = array(
  6. 'Baidu,http://www.baidu.com/',
  7. 'dedecms,http://bbs. it-home.org/',
  8. );
  9. $str = 'Search dedecms in Baidu';
  10. $out = keylink ($str, $link, 1);
  11. //$str original character $link, replace link Array, 3 replacement times
  12. echo $out;
  13. function _sortDesc($a, $b) {
  14. return (strlen ( $a [0] ) < strlen ( $b [0] )) ? 1 : – 1;
  15. }
  16. function keylink($str, $link, $count = 1) {
  17. $linkDefs = $link;
  18. $linkMap = array ();
  19. foreach ( $linkDefs as $row ) {
  20. $linkMap [] = explode ( ',', $row );
  21. }
  22. foreach ( $linkMap as $row ) {
  23. $str = preg_replace ( '/(s*)(' . $row [0] . ')(s*}
  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 < count ( $linkMap ); $j ++)
  30. {
  31. $subKwd = $ linkMap [$j] [0];
  32. //If it contains other keywords, temporarily replace it with other strings
  33. if (strpos ( $kwd, $subKwd ) !== false)
  34. {
  35. $tmpKwd = '{' . md5 ( $subKwd ) . '}';
  36. $kwd = str_replace ( $subKwd, $tmpKwd, $kwd );
  37. $tmpKwds [$tmpKwd] = $subKwd;
  38. }
  39. }
  40. //Replace text with link
  41. $str = preg_replace ( '/(' . $row [0] . ')/sui', '' . $kwd . '', $str, $count );
  42. }
  43. //Replace the string that replaces the subkeyword back
  44. foreach ( $tmpKwds as $tmp => $kwd ) {
  45. $str = str_replace ( $tmp, $kwd, $str );
  46. }
  47. return $str;
  48. }
  49. ?>
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template