doukui4786 2012-01-16 07:45
浏览 15
已采纳

如何使用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!

  • 写回答

1条回答 默认 最新

  • ds355020 2012-01-16 08:04
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器