Kiran
Kiran

Reputation: 61

How to extract single line in block of HTML code

I have contents as:

<meta property="og:type" content="article" />
<meta property="og:url" content="http://website/fox/" />
<meta property="og:site_name" content="The Fox" />
<meta property="og:image" content="http://images.Fox.com/2014/09/foxandforset.gif?w=209" />
<meta property="og:title" content="Fox goes to forest" />

My requirement here is to extract/get one line, i.e. meta property=og:image.. so result should contain:

<meta property="og:image" content="http://images.Fox.com/2014/09/foxandforset.gif?w=209" />

Upvotes: 2

Views: 252

Answers (2)

user3942918
user3942918

Reputation: 26405

Extracting a "line" of HTML, or using regular expressions to parse HTML in general, is brittle. More robust would be to use an HTML parser such as the support provided by the DOM extension.

Example:

$html = <<<'HTML'
<meta property="og:type" content="article" />
<meta property="og:url" content="http://website/fox/" />
<meta property="og:site_name" content="The Fox" />
<meta property="og:image" content="http://images.Fox.com/2014/09/foxandforset.gif?w=209" />
<meta property="og:title" content="Fox goes to forest" />
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodes = $xpath->query('//meta[@property="og:image"]');

foreach ($nodes as $node) {
    echo $dom->saveHTML($node);
}

Output:

<meta property="og:image" content="http://images.Fox.com/2014/09/foxandforset.gif?w=209">

Upvotes: 1

vks
vks

Reputation: 67988

^<meta property="og:image".*$

Try this.Set flags m and g.See demo.

http://regex101.com/r/hQ1rP0/48

Upvotes: 1

Related Questions