Solution of PHP Regular Expression Replacing Blank Space after Site Keyword Link

  • 2021-07-18 07:40:59
  • OfStack

I don't know if the title is suitable or not. The specific situation is as follows: The website wants to add keyword link function, and then needs to match and replace the content of the article with regular expressions, and then uses preg_replace function. The replacement program code is as follows:


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

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

// Replace the original link with text 
foreach($linkMap as $row) {
$content = preg_replace('/(<a.*?>\s*)('.$row[0].')(\s*<\/a>)/sui', $row[0], $content);
}

// Sort keywords from long to short 
usort($linkMap, '_sortDesc');
//var_dump($linkMap);

$tmpKwds = array(); // Store temporarily replaced sub-keywords 

$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 other keywords are included, temporarily replace them with other strings, such as   Tea leaves   Become  
if(strpos($kwd, $subKwd) !== false) {
$tmpKwd = '';
$kwd = str_replace($subKwd, $tmpKwd, $kwd);
$tmpKwds[$tmpKwd] = $subKwd;
}
}
// Replace text with links 
require(MLEINC.'/config/globals.config.php');
$th_num = $config['keyword_num']; // Number of keyword replacements 
$content = preg_replace('/('.$row[0].')/sui', '<a href="'.$row[1].'">'.$kwd.'</a>', $content, $th_num ,$count); //  All matches will be replaced 
$k_count+=$count;
}

// Replace the string that replaces the subkeyword back 
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 is found from the Internet, and then the local test is normal. The local environment is php 5.3 service is 5.2. After uploading to the Internet, the submission shows blank. 1 began to consider the PHP version problem, thinking that it is the difference between ereg and preg, and it is still not good after replacement. Later, when I read it online, I found that some netizens said that it is enough to adjust pcre.backtrack_limit and pcre.recursion_limit. I tried it and it was OK. It seems to be a configuration problem, but in 1 case, the default configuration of PHP should be no problem, and this program written by myself is still not good enough!


Related articles: