How can I find the contents of the first h3 tag?

I am looking for a regex to find the contents of the first tag <h3>. What can i use there?

+3
source share
8 answers

Instead of regular expressions, use the php DOM parser. You are looking for something like this (warning of unverified code):

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($html_content);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$items = $domx->query("//h3[position() = 1]");

echo $items->item(0)->textContent;
+4
source

DOM Approach:

<?php

$html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
</head>
<body>

<h1>Lorem ipsum<h1>
<h2>Dolor sit amet<h2>
<h3>Duis quis velit est<h3>
<p>Cras non tempor est.</p>
<p>Maecenas nec libero leo.</p>
<h3>Nulla eu ligula est</h3>
<p>Suspendisse potenti.</p>

</body>
</html>
';

$doc = new DOMDocument;
$doc->loadHTML($html);

$titles = $doc->getElementsByTagName('h3');
if( !is_null($titles->item(0)) ){
    echo $titles->item(0)->nodeValue;
}

?>
+3
source

, :

preg_match( '#<h3[^>]*>(.*?)</h3>#i', $text, $match );
echo $match[1];

, HTML-, .

+2

, HTML . , ...

$doc = new DOMDocument();
$doc->loadHTML($text);
$headings = $doc->getElementsByTagName('h3');
$heading = $headings->item(0);
$heading_value = (isset($heading->nodeValue)) ? $heading->nodeValue : 'Header not found';
+2

: HTML-. , H3 .

preg_match_all('/<h3[^>]*>(.*?)<\/h3>/si', $source, $matches);

$matches H3 tagas.

+1

xpath,

"/html/body/h3[0]"

h3 node.

, html.

+1

PHP has the ability to parse HTML DOM on its own - you almost certainly want to use this instead of a regular expression.

See this page for more details: http://php.net/manual/en/book.dom.php

And check the related questions on the right for people asking very similar questions.

0
source
preg_match("/&lt;h3&gt;(.*)&lt;\/h3&gt;/", $search_in_this_string, $put_matches_in_this_var);
-1
source

Source: https://habr.com/ru/post/1767883/


All Articles