我在数据库中保存了一个html代码。我想将特定的单词(例如:学校,书籍,chock)转换为链接(标签),我希望转换是安全的。
一种可能的方法是先删除所有标签,这样我就不会添加一个不应该的链接。但在这种情况下,我将放弃格式化,我不希望这样。
为了澄清这个问题,我将向您展示一些有问题的代码示例,如果我尝试将“书籍”更改为“书籍”,则会出现错误:
1. <div class="books">lorem ipsum dolor....
2. <a href = "http://www.example.com">all of the books in the store</a>
提前致谢!
答案 0 :(得分:3)
这是一种使用字符串搜索和替换的方法。
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