从字符串中删除 HTML 标记,但保留 href 属性

本文关键字:保留 href 属性 标记 字符串 删除 HTML | 更新日期: 2023-09-27 17:56:51

如果问题的标题不清楚。

我想解析一下:

<p><a rel="nofollow" data-xxx="797998" href="http://www.stackoverflow.com">StackOverflow</a> for the win</p>

对此:

http://www.stackoverflow.com StackOverflow for the win

我发现了很多关于如何使用 HTML 解析器甚至正则表达式删除 HTML 标签的有用问题,但没有关于保留 HTML 属性的问题。

如何做到这一点?

从字符串中删除 HTML 标记,但保留 href 属性

这应该可以通过正则表达式替换来执行您想要的操作。

string html = "<p><a rel='"nofollow'" data-xxx='"797998'" href='"http://www.stackoverflow.com'">StackOverflow</a> for the win</p>";
string parsed = Regex.Replace(html, "<[^>]+href='"([^'"]+)'"[^>]*>", "$1 ");
parsed = Regex.Replace(parsed, "<[^>]+>", "");

首先提取 href 属性并删除包含的标记。第二次运行将删除所有剩余的标记,包括结束标记等。

有点具体,但它可以满足您的要求。

var str = '<p><a rel="nofollow" data-xxx="797998" href="http://www.stackoverflow.com">StackOverflow</a> for the win</p>';
var str = str.replace('</a>', '');
var str = str.replace('</p>', '');
var str = str.replace('">', '');
var p = str.indexOf('href="');
console.log(str.slice(p + 'href="'.length));

使用字符串的示例:

private string ParseAttribute(string input, string attributeName)
{
    int startIndex = input.IndexOf(attributeName + "='"");
    if (startIndex >= 0)
    {
        startIndex += attributeName.Length + 2;
        int endIndex = input.IndexOf('"', startIndex);
        if (endIndex >= 0)
            return input.Substring(startIndex, endIndex - startIndex);
    }
    return string.Empty;
}
// usage
string html = "<p><a rel='"nofollow'" data-xxx='"797998'" href='"http://www.stackoverflow.com'">StackOverflow</a> for the win</p>";
Console.WriteLine(ParseAttribute(html, "href"));

此代码可能有其弱点,但会执行您的要求。

编辑:好的,我看到我错过了你也想要元素内容。但我还是留下了这个代码片段。也许它以某种方式有所帮助。

可以这样简单:

String yourinput = "...";
result = Regex.Replace(yourinput, "<.*?>", String.Empty);