Home > Article > Backend Development > PHP method to add keywords and links in articles
You can use the built-in function usort to sort two-dimensional arrays. The code is as follows:
Extract all html tags
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. |