Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substring <img src="myimage" /> from a string? [duplicate]

Tags:

c#

.net

How can I take an < img tag from string? Sample string is given below. But too bad name and surname parts are dynamic and sometimes image names are numbers...

Lorem ipsum dolor sit amet <img src='http://www.mydomain.com/images/name_surname.jpg' /> Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

What I've tried so far:

sMyText.Substring(sDescription.IndexOf("<img"), count?!);

how to count the who image character length? This is where I fail. Please help..

like image 908
Cute Bear Avatar asked Jun 27 '26 21:06

Cute Bear


2 Answers

Use regular expressions.

string sMyText = "Lorem ipsum dolor sit amet <img src='http://www.mydomain.com/images/name_surname.jpg' /> Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.";

Match match = Regex.Match(sMyText, "<img[^>]+>");

if (match.Success)
    Console.WriteLine(match.Value);
like image 116
TheQ Avatar answered Jun 29 '26 10:06

TheQ


I really don't like parsing html with a regex (see this question). I'd suggest using something like HtmlAgilityPack. It may seem overkill for your example but you'll save yourself a lot of pain in the future!

var document = new HtmlDocument();
document.LoadHtml(html);
var links = document.DocumentNode.Descendants("img");
like image 39
Liath Avatar answered Jun 29 '26 12:06

Liath