Procedure:
This problem seems simple, but it is a bit difficult to do. I implemented it in a less intelligent way:
1. Replace existing keyword links with text
2. Sort keywords from long to short
3. Replace the long-to-short keyword with the link, and search for any other keywords. If so, replace the subkeyword with the MD5 value of the {subkeyword}
4. Replace the MD5 value of {subkeyword }.
<? Header ("Content-Type: text/html; charset = UTF-8"); function _ sortdesc ($ A, $ B) {return (strlen ($ A [0]) <strlen ($ B [0])? 1:-1 ;}$ linkdefs = array ('tea leaves, 111.htm', 'Chinese tea overview, 222.htm',); $ linkmap = array (); foreach ($ linkdefs as $ row) {$ linkmap [] = explode (',', $ row) ;}$ STR = 'Here is the tea link. <Br/> here is the link to the Chinese tea big view. <Br/> here is the existing link of <a href = "111.html"> tea </a>. <Br/> here is the existing link of <a href = "222.html"> China Tea dashboard </a>. <Br/> '; // replace the original link with the text foreach ($ linkmap as $ row) {$ STR = preg_replace ('/(<A. *?> \ S *)('. $ row [0]. ') (\ s * <\/A>)/sui', $ row [0], $ Str);} // sort usort ($ linkmap, '_ sortdesc'); // var_dump ($ linkmap); $ tmpkwds = array (); // store the subkeyword 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, replace them with other strings temporarily, for example, tea leaves into if (strpos ($ KWD, $ subkwd )! = False) {$ tmpkwd = ''; $ KWD = str_replace ($ subkwd, $ tmpkwd, $ KWD); $ tmpkwds [$ tmpkwd] = $ subkwd ;}} // Replace the text with the link $ STR = preg_replace ('/('. $ row [0]. ')/sui',' <a href = "'. $ row [1]. '"> '. $ KWD. '</a>', $ STR,-1 ); // all matching items will be replaced} // Replace the string that replaces the sub-Keyword with foreach ($ tmpkwds as $ TMP => $ KWD) {$ STR = str_replace ($ TMP, $ KWD, $ Str) ;}echo $ STR ;?>
Function preg_replace ()
Reference http://baike.baidu.com/view/4463003.htm