-
- /**
- * Add article keywords and internal links
- * by bbs.it-home.org
- */
- $link = array(
- 'Baidu,http://www.baidu.com/',
- 'dedecms,http://bbs. it-home.org/',
- );
- $str = 'Search dedecms in Baidu';
- $out = keylink ($str, $link, 1);
- //$str original character $link, replace link Array, 3 replacement 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*}
- usort ( $linkMap, '_sortDesc' );
- $tmpKwds = array ();
- foreach ( $linkMap as $i => $ row )
- {
- list ( $kwd, $url ) = $row;
- for($j = $i + 1; $j < count ( $linkMap ); $j ++)
- {
- $subKwd = $ linkMap [$j] [0];
- //If it contains other keywords, temporarily replace it 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 back
- foreach ( $tmpKwds as $tmp => $kwd ) {
- $str = str_replace ( $tmp, $kwd, $str );
- }
- return $str;
- }
- ?>
Copy code
|