Home  >  Article  >  Backend Development  >  PHP method to add keywords and links in articles

PHP method to add keywords and links in articles

WBOY
WBOYOriginal
2016-07-25 09:11:031457browse
  1. $keywordArray = array(
  2. array('process', 'http://www.01happy.com/linux-ps-view-process/')
  3. , array('daemon process', 'http: //www.01happy.com/linux-python-daemon/')
  4. );
Copy code

You can use the built-in function usort to sort two-dimensional arrays. The code is as follows:

  1. usort($keywordArray, function($a, $b) {
  2. $al = strlen($a[0]);
  3. $bl = strlen($b[0]);
  4. if ($ al == $bl)
  5. return 0;
  6. return ($al > $bl) ? -1 : 1;
  7. });
Copy code

Extract all html tags

  1. preg_match_all('/]*>/', $content, $match);
  2. if (isset($match[0] )) {
  3. $htmlTagArray = $match[0];
  4. }
Copy code

The regular rule here is to extract all the content wrapped by . The author believes that whenever the number needs to be displayed as content, should be replaced with the escape character <>. All content enclosed by can be considered as tags. In fact, browsers do this too, and many online text editors will automatically escape these characters.

Split content and save to array $noTagContentArray = preg_split('/?[a-zA-Z]+[^>]*>/', $content);

The regular expression used here is the same as the regular expression used to extract html tags above.

Loop through the divided content array and replace keyword links The processing method here is to first replace the keywords with md5 values, and then replace the md5 values ​​with keywords with links. The reason for this processing is to solve the problem of inclusion between keywords. In addition, the author once considered imploding the divided content array into a string, so that there would be no need for loop replacement. However, I was worried that the string after imploding would form keywords at the splicing point, so I did not do it this way.

Combine extracted html tags and processed content This step is relatively simple, just splice them one by one and you're done. It should be noted that the length of the html tag array will be 1 smaller than the length of the divided content array, so when fetching the tag, use isset to judge. The above content has been tested many times and there is no problem. If you have any questions, you are welcome to enter the QQ group of this site: 161228069 for communication.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP null value judgmentNext article:PHP null value judgment