Home >Backend Development >PHP Tutorial >Automatically add links to keywords in php_PHP tutorial
Some time ago, I wanted to connect keywords to the description content of my zencart site group, but because there were too many keywords, I wanted to write a program to automatically perform this function. However, I have not seriously learned the PHP language, so I referred to a lot of information on the Internet. I compiled a function myself
function zen_key_replace($str){
$array_first = array(
array('2012 New UGG Boots','link1.html'),
array('black ugg boots','link2.html'),
array('cheap ugg boots','link3.html'),
array('cheapest ugg boots','link4.html'),
array('discount ugg boots','link5.html'),
array('girls ugg boots','link6.html'),
array('grey ugg boots','link7.html'),
array('ugg boots','link8.html')
);
$array_last = array();
foreach($array_first as $key=>$value){
$array_last[$key] = array('TFXS00'.$key, $value[0], ''.$value[0].'');
}
$count = count($array_last);
for($i=0; $i<$count; $i++){
for($j=$count-1; $j>$i; $j--){
//If the length of the next element is greater than the previous one, swap the position
If(strlen($array_last[$j][1]) > strlen($array_last[$j-1][1])){
$tmp = $array_last[$j];
$array_last[$j] = $array_last[$j-1];
$array_last[$j-1] = $tmp;
}
}
}
$keys=$array_last;
foreach($keys as $nkeys){
$str= str_ireplace($nkeys[1], $nkeys[0], $str);
}
foreach($keys as $nkeys){
$str= str_ireplace($nkeys[0], $nkeys[2], $str);
}
Return $str;
}
Example: www.2cto.com
$str = "Today is January 9, 2012, ugg boots website, seo is search engine optimization for girls ugg boots, css+div, Photoshop, Flash, HTML, CSS, Dreamweaver, Fireworks, ASP, PHP, JSP, ASP .NET";
echo zen_key_replace(stripslashes($str));//Call this function where the article content is output. $str is the article content
?>
The first is an array sorting, with longer keywords given priority, because if the related short keywords are at the front, the longer keywords will not be replaced. If ugg boot has been replaced first, then ugg boot sale will have become TFXS008 sale. It will not be replaced successfully
Then there is a replacement. The reason for replacing it first with TFXS001 is so that in the second replacement, it will not be replaced multiple times because of frequently occurring keywords like ugg boots. . Similar to the situation of 2012 New UGG Boots. .
Above, I feel that this function is still too simple. You can also add replacement number control and write keywords and link data into the database. However, I have just started learning these things and I don’t know how to do them in many places. I will continue to work hard. of.