如何使用PHP在html文档中安全地添加标签

I have an html code saved in a database. I want to convert specific words (for example: school, books, chock) into links ( tags) and I want the conversion to be safe.

One possible way to do that is to strip all tags first, so that I will not add a link where it is not supposed to be. But in this case I will loose the formatting and I don't want that.

To clarify the problem I will show you some examples for a problematic code, where an error will occur if I try to change "books" into "books:

1.   <div class="books">lorem ipsum dolor....
2.   <a href = "http://www.example.com">all of the books in the store</a>

Thanks in advance!

Here is a way to do it using just string search and replace.

for each word,
  do a search in the html code.
  for each found word,

    if there there is a "<" somewhere on the left side of the found word then

      if there is no ">" between the closest "<" and the start of the found word then
        The word is in a html tag? Ignore the word.
      end if
    end if

    if there is a "<a " somewhere on the left side of the word then
      if there is no "</a>" between the closest "<a " and the start of the found word then
        The word is already a link? Ignore the word.
      end if
    end if

    if none of the conditions above matches then
      Yeah! Found the word. Put in your link.
    end if
  end for
end for