PHPRegex替換網站關鍵字連結後空白的問題解決

來源:互聯網
上載者:User

標籤:des   http   os   io   使用   ar   for   div   問題   

標題這樣不知道合適不合適。具體的情況是這樣的:網站要增加關鍵字連結功能,然後需要對文章的內容進行Regex匹配並替換,然後使用了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.*?>\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的預設配置應該沒啥問題,我自己寫的這程式還是不夠好!

PHPRegex替換網站關鍵字連結後空白的問題解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.