Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text between HTML tags [duplicate]

Ok, This is a pretty basic question im sure but im new to PHP and haven't been able to figure it out. The input string is $data im trying to continue to pull and only use the first match. Is the below incorrect? This may not even be the best way to perform the action, im just trying to pull the contents in between two html tags (first set found) and discard the rest of the data. I know there are similar questions, ive read them all, my question is a mix, if theres a better way to do this and how i can define the match as the new input for the rest of the remaining code. If i change $matches to $data2 and use it from there on out it returns errors.

preg_match('/<h2>(.*?)<\/h2>/s', $data, $matches);
like image 357
Ryan Cooper Avatar asked Apr 18 '11 07:04

Ryan Cooper


3 Answers

Don't parse HTML via preg_match, use this PHP class instead:

The DOMDocument class

Example:

<?php 

$html= "<p>hi</p>
<h1>H1 title</h1>
<h2>H2 title</h2>
<h3>H2 title</h3>";
 // a new dom object 
 $dom = new domDocument('1.0', 'utf-8'); 
 // load the html into the object 
 $dom->loadHTML($html); 
 //discard white space 
 $dom->preserveWhiteSpace = false; 
 $hTwo= $dom->getElementsByTagName('h2'); // here u use your desired tag
 echo $hTwo->item(0)->nodeValue; 
 //will return "H2 title";
 ?>

Reference

like image 112
diEcho Avatar answered Nov 19 '22 20:11

diEcho


You could do it this way::

$h1 = preg_replace('/<h1[^>]*?>([\\s\\S]*?)<\/h1>/',
'\\1', $h1);

This will Strip off or unwrap the TEXT from the <H1></H1> HTML Tags

like image 30
ErickBest Avatar answered Nov 19 '22 22:11

ErickBest


Using regular expressions is generally a good idea for your problem.

When you look at http://php.net/preg_match you see that $matches will be an array, since there may be more than one match. Try

print_r($matches);

to get an idea of how the result looks, and then pick the right index.

EDIT:

If there is a match, then you can get the text extracted between the parenthesis-group with

print($matches[1]);

If you had more than one parenthesis-group they would be numbered 2, 3 etc. You should also consider the case when there is no match, in which case the array will have the size of 0.

like image 20
Erik Avatar answered Nov 19 '22 20:11

Erik