PHP 文章内容中的关键词替换加链接
/**
*对内容中的关键词添加链接
*只处理第一次出现的关键词,对已有链接的关键不会再加链接,支持中英文
*$content:string 原字符串
*$keyword:string 关键词
*$link:string,链接
*/
public static function yang_keyword_link($content,$keyword,$link){
//排除图片中的关键词
$content = preg_replace( '|(<img[^>]*?)('.$keyword.')([^>]*?>)|U', '$1%&&&&&%$3', $content);
$regEx = '/(?!((<.*?)|(<a.*?)))('.$keyword.')(?!(([^<>]*?)>)|([^>]*?<\/a>))/si';
$url='<a href="'.$link.'" target="_blank" class="content_guanjianci">'.$keyword.'</a>';
$content = preg_replace($regEx,$url,$content,1);
//还原图片中的关键词
$content=str_replace('%&&&&&%',$keyword,$content);
return $content;
}
文章来自:http://www.phpxs.com/post/3489/
---------------其它补充--------------
Example #2 preg_replace()中使用基于索引的数组
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
以上例程会输出:
The bear black slow jumped over the lazy dog.
对模式和替换内容按key进行排序我们可以得到期望的结果。
<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>
以上例程会输出:
The slow black bear jumped over the lazy dog.
Example #3 替换一些值
<?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
'/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>
以上例程会输出:
$startDate = 5/27/1999
最后由 Leo 编辑于2017年02月06日 09:57