|
標(biāo)題這樣不知道合適不合適。具體的情況是這樣的:網(wǎng)站要增加關(guān)鍵字鏈接功能,然后需要對文章的內(nèi)容進(jìn)行正則表達(dá)式匹配并替換,然后使用了preg_replace函數(shù)。替換的程序代碼如下:
function ReplaceKeyword($linkDefs,$content){$linkMap = array();/*foreach($linkDefs as $row) {$linkMap[] = explode(',', $row);}*/$linkMap = $linkDefs;//把原有的鏈接替換成文字foreach($linkMap as $row) {$content = preg_replace('/(<a.*?>/s*)('.$row[0].')(/s*<//a>)/sui', $row[0], $content);}//關(guān)鍵字從長至短排序usort($linkMap, '_sortDesc');//var_dump($linkMap);$tmpKwds = array(); //存放暫時被替換的子關(guān)鍵字$k_count=0;foreach($linkMap as $i=>$row) {list($kwd, $url) = $row;for($j=$i+1; $j<count($linkMap); $j++) {$subKwd = $linkMap[$j][0];//如果包含其他關(guān)鍵字,暫時替換成其他字符串,如 茶葉 變成 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']; //關(guān)鍵字替換次數(shù)$content = preg_replace('/('.$row[0].')/sui', '<a href="'.$row[1].'">'.$kwd.'</a>', $content, $th_num ,$count); // 所有的匹配項都會被替換$k_count+=$count;}//把代替子關(guān)鍵字的字符串替換回來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);}
程序是從網(wǎng)上找的,然后在本地測試是正常的,本地環(huán)境為php 5.3 服務(wù)是5.2的,上傳到網(wǎng)上去后,提交則顯示空白,一開始考慮是php版本問題,以為是ereg preg的區(qū)別,替換后還是不行。后來網(wǎng)上看,發(fā)現(xiàn)有網(wǎng)友說調(diào)整大pcre.backtrack_limit和pcre.recursion_limit就行,我試了下,果然可以了。看來是配置問題,不過一般情況下,php的默認(rèn)配置應(yīng)該沒啥問題,我自己寫的這程序還是不夠好!
php技術(shù):PHP正則表達(dá)式替換站點(diǎn)關(guān)鍵字鏈接后空白的解決方法,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。