Page 1 of 1
Pulling out a string between two tags
Posted: Tue Jun 21, 2005 4:52 am
by gorm
Hi
I am attempting to pull a sub string from within a html tag:
Code: Select all
<? PHP
$str = "some text<br> <h1>The Heading</h1> some more text<br>";
?>
What I want to be able to do is set a variable to what ever is inside the h1 tags.
Thanks in advance
Posted: Tue Jun 21, 2005 4:57 am
by Chris Corbyn
Moved to regex...
Posted: Tue Jun 21, 2005 5:45 am
by Chris Corbyn
This is reasonably straight forward using regex. The function below might help you
Code: Select all
function getInnerHTML($tagname, $string) {
$pattern = '#<'.$tagname.'[^>]*>(.*?)</'.$tagname.'>#is'; //Backreference 1 is innerHTML
preg_match_all($pattern, $string, $matches); //Multi-dimensional array
return $matches[1]; //Array
}
//Example
$string = "
This <span>string</span> contains
<span style=\"color:red\">red</span> text!
";
$spans = getInnerHTML('span', $string);
/*
Array (
[0] => string
[1] > red
)
*/
Posted: Tue Jun 21, 2005 6:32 am
by gorm
Nice one - works like a charm. Thank you very much