-
- // Example use: $spanned = codeWords($string_containing_keywords);
- // My site: andrew.dx.am
- // Using colour==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 = "/^(?:(?!//).)*Kb(" . $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 = "" . $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', 'while', 'with');
- $keywords2 = $keywords;
- array_walk($keywords, 'onlyWholeWords');
- array_walk($keywords2, 'addSpan', 'blue');
- $code = preg_replace($keywords, $keywords2, $code);
- return $code;
- }
复制代码
二、php自动给文章加关键词链接
自动给文章加关键词链接的php函数代码。
代码:
-
-
$link = array( - '百度,http://www.baidu.com/',
- 'php教程,http://bbs.it-home.org/wb/php/',
- '脚本学堂,http://bbs.it-home.org/',
- );
- $str = '在百度中搜索php教程就可以到程序员之家提供的php编程文章
- 此处放置需要替换的内容。';
- $out=keylink($str,$link,1); //$str 原始字符 $link,替换链接数组, 3替换次数
- 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*)/sui', '', $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(strpos($kwd, $subKwd) !== false) {
- $tmpKwd = '{'.md5($subKwd).'}';
- $kwd = str_replace($subKwd, $tmpKwd, $kwd);
- $tmpKwds[$tmpKwd] = $subKwd;
- }
- }
- //把文字替换成链接
- $str = preg_replace('/('.$row[0].')/sui', ''.$kwd.'', $str, $count);
- }
//把代替子关键字的字符串替换回来
- foreach($tmpKwds as $tmp=>$kwd) {
- $str = str_replace($tmp, $kwd, $str);
- }
- return $str;
- }
- ?>
复制代码
|