I don’t know if this title is appropriate or not. The specific situation is this: the website wants to add a keyword link function, and then the content of the article needs to be matched and replaced with regular expressions, and then the preg_replace function is used. The replaced program code is as follows:
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); }
The program was found online and tested locally. It was normal. The local environment was PHP 5.3 and the service was 5.2. After uploading it to the Internet, the submission showed blank. At first, I thought it was a PHP version problem and thought it was ereg. The difference between preg, it still doesn’t work after replacement. Later, when I looked online, I found that some netizens said that just adjusting the pcre.backtrack_limit and pcre.recursion_limit would be enough. I tried it, and it worked. It seems to be a configuration problem, but under normal circumstances, the default configuration of PHP should be fine. The program I wrote myself is still not good enough!
I can write like this. I have tried it with IE6 and FIREFOX 3.0, and there is no problem.