Home >Backend Development >PHP Tutorial >PHP正则表达式替换站点关键字链接后空白的解决方法_php技巧

PHP正则表达式替换站点关键字链接后空白的解决方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:36:011017browse

标题这样不知道合适不合适。具体的情况是这样的:网站要增加关键字链接功能,然后需要对文章的内容进行正则表达式匹配并替换,然后使用了preg_replace函数。替换的程序代码如下:

function ReplaceKeyword($linkDefs,$content){
$linkMap = array();

/*foreach($linkDefs as $row) {
$linkMap[] = explode(',', $row);
}*/
$linkMap = $linkDefs;

//把原有的链接替换成文字
foreach($linkMap as $row) {
$content = preg_replace('/(<a.*&#63;>\s*)('.$row[0].')(\s*<\/a>)/sui', $row[0], $content);
}

//关键字从长至短排序
usort($linkMap, '_sortDesc');
//var_dump($linkMap);

$tmpKwds = array(); //存放暂时被替换的子关键字

$k_count=0;
foreach($linkMap as $i=>$row) {
list($kwd, $url) = $row;
for($j=$i+1; $j<count($linkMap); $j++) {
$subKwd = $linkMap[$j][0];
//如果包含其他关键字,暂时替换成其他字符串,如 茶叶 变成 
if(strpos($kwd, $subKwd) !== false) {
$tmpKwd = '';
$kwd = str_replace($subKwd, $tmpKwd, $kwd);
$tmpKwds[$tmpKwd] = $subKwd;
}
}
//把文字替换成链接
require(MLEINC.'/config/globals.config.php');
$th_num = $config['keyword_num']; //关键字替换次数
$content = preg_replace('/('.$row[0].')/sui', '<a href="'.$row[1].'">'.$kwd.'</a>', $content, $th_num ,$count); // 所有的匹配项都会被替换
$k_count+=$count;
}

//把代替子关键字的字符串替换回来
foreach($tmpKwds as $tmp=>$kwd) {
$content = str_replace($tmp, $kwd, $content);
}
$result = array($content,$k_count);

return $result;
unset($result);
unset($tmp);
unset($tmpKwds);
unset($kwd);
unset($count);
unset($config);
unset($linkMap);
unset($linkDefs);
unset($tmpKwd);
unset($content);
unset($th_num);
unset($row);
unset($k_count);
}

程序是从网上找的,然后在本地测试是正常的,本地环境为php 5.3 服务是5.2的,上传到网上去后,提交则显示空白,一开始考虑是PHP版本问题,以为是ereg preg的区别,替换后还是不行。后来网上看,发现有网友说调整大pcre.backtrack_limit和pcre.recursion_limit就行,我试了下,果然可以了。看来是配置问题,不过一般情况下,PHP的默认配置应该没啥问题,我自己写的这程序还是不够好!

Statement:
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