<p> 用 C# 替换任何标记 html 中的文本



我正在尝试替换我在 <p> tag中的任何文本,如果我有关注html:

<p><br />
<html><br />
<body></p>
<p><h1>My First JavaScript</h1></p>
<p><button type="button"<br />
onclick="document.getElementById('demo').innerHTML = Date()"><br />
Click me to display Date and Time.</button></p>
<p><p id="demo"></p></p>
<p></body><br />
</html> <br />
</p>
</div>

我想更改<p>标签中的任何文本,然后更换特殊字符,我尝试过的内容:

string pTag = "<p>";
        int pLength = pTag.Length;
        int index = input.IndexOf(pTag, StringComparison.Ordinal);
        while (index > 0)
        {
            int lastIndex = input.IndexOf("</p>", index);
            if (lastIndex == index)
                break;
            var subString = input.Substring(index + pLength, lastIndex - index - pLength);
            var newsubString = System.Security.SecurityElement.Escape(subString);
            input = input.Replace(subString, newsubString);
            index = lastIndex;
        }

但是我的代码仅更改第一个项目,有什么建议吗?

谢谢!

您正在击中您的break;

找到第一个标签并进行了更改后说:

index = lastIndex;

下次循环开始并命中:

int lastIndex = input.IndexOf("</p>", index);

将被击中相同的索引,并将突破退出循环。

更改为:

int lastIndex = input.IndexOf("</p>", index + 4);

和每当索引方法返回-1时断开(指示它尚未找到并出现指定字符串)

我们去:

        string html = "<p>oldtext</p>";
        string open = "<p>";
        string close = "</p>";
        int start = html.IndexOf(open);
        int end = html.IndexOf(close);
        string result = html.Substring(start + open.Length, end - (close.Length - 1));
        html = html.Replace(result, "newtext");

最新更新