Html Agility Pack + C #을 사용하여 텍스트를 HTML 링크로 변환하려면 어떻게해야합니까?
예 : "www.stackoverflow.com은 매우 멋진 사이트입니다."
산출:
"<a href="www.stackoverflow.com">www.stackoverflow.com</a> is a very cool site."
답변 해 주셔서 감사합니다 @ user1778606. Regex 비트를 여전히 사용하지만이 작업이 있습니다. 그것은 훨씬 더 안전하고 안전하게 작동합니다 (즉, 하이퍼 링크와 href 속성 내에서 하이퍼 링크를 생성하지 않습니다).
//convert text to html
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(inputString);
// \w* - means it can start with any alphanumeric charactar
// \s+ - was placed to replace all white spaces (when there is more than one word).
// \b - set bounderies for the keyword
const string pattern = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)";
//get all elements text propery except for anchor element
var nodes = doc.DocumentNode.SelectNodes("//text()[not(ancestor::a)]") ?? new HtmlAgilityPack.HtmlNodeCollection(null);
foreach (var node in nodes)
{
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
node.InnerHtml = regex.Replace(node.InnerHtml, "<a href=\"$1\">$1</a>").Replace("href=\"www", "href=\"http://www");
}
return doc.DocumentNode.OuterHtml;
나는 그것을 시도하지는 않았지만, 가능하다고 확신한다.
문서의 고정 된 문자열을 링크로 대체하는 방법은 다음과 같습니다.
URL을 정규식하는 방법을 보여줍니다.
그것들을 합치면 가능할 것입니다.
의사 코드
모든 텍스트 노드를 선택하십시오.
각 노드에 대해
내부 텍스트를 얻는다.
텍스트에서 URL 찾기 (regex 사용?)
찾은 각 URL에 대해URL의 텍스트를 문자열 리터럴 링크 태그 (a href = etc ...)로 바꿉니다.