Comment puis-je convertir un lien URL en HTML à partir d'un texte utilisant Html Agility Pack + c #?
Par exemple: "www.stackoverflow.com est un site très cool."
Sortie:
"<a href="www.stackoverflow.com">www.stackoverflow.com</a> is a very cool site."
Merci @ user1778606 pour votre réponse. Je travaille bien que cela utilise encore un peu de Regex. Cela fonctionne beaucoup mieux et est plus sûr (c’est-à-dire qu’il ne créera jamais de lien hypertexte entre les liens hypertexte et l’attribut 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;
Je suis presque sûr que c'est possible, même si je ne l'ai pas essayé.
Voici comment remplacer une chaîne fixe dans un document par des liens
Rechercher un mot clé dans le texte lorsque le mot clé correspond à certaines conditions - C #
Heres comment regex pour les urls
Mettez ceux-ci ensemble et cela devrait être possible.
Pseudocode
sélectionner tous les nœuds de texte
pour chaque noeud
obtenir le texte intérieur
trouve les urls dans le texte (utilisez regex?)
pour chaque URL trouvéeremplace le texte de l'URL par la chaîne tag literal link (a href = etc ...)