我想收到一个包含文本中所有h1标记值的数组
例如,如果这个给定的输入字符串:
<h1>hello</h1>
<p>random text</p>
<h1>title number two!</h1>
Run Code Online (Sandbox Code Playgroud)
我需要收到一个包含这个的数组:
titles[0] = 'hello',
titles[1] = 'title number two!'
Run Code Online (Sandbox Code Playgroud)
我已经弄清楚如何获取字符串的第一个h1值,但我需要给定字符串中所有h1标签的所有值.
我目前正在使用它来接收第一个标签:
function getTextBetweenTags($string, $tagname)
{
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
Run Code Online (Sandbox Code Playgroud)
我传递了我想要解析的字符串,并将其作为$ tagname放入"h1".我自己没有写它,我一直在尝试编辑代码来做我想要的但没有真正有效.
我希望有人可以帮助我.
提前致谢.
Ser*_*min 32
你可以使用simplehtmldom:
function getTextBetweenTags($string, $tagname) {
// Create DOM from string
$html = str_get_html($string);
$titles = array();
// Find all tags
foreach($html->find($tagname) as $element) {
$titles[] = $element->plaintext;
}
}
Run Code Online (Sandbox Code Playgroud)
Wri*_*ken 22
function getTextBetweenTags($string, $tagname){
$d = new DOMDocument();
$d->loadHTML($string);
$return = array();
foreach($d->getElementsByTagName($tagname) as $item){
$return[] = $item->textContent;
}
return $return;
}
Run Code Online (Sandbox Code Playgroud)
DOM的替代品.在内存出现问题时使用.
$html = <<< HTML
<html>
<h1>hello<span>world</span></h1>
<p>random text</p>
<h1>title number two!</h1>
</html>
HTML;
$reader = new XMLReader;
$reader->xml($html);
while($reader->read() !== FALSE) {
if($reader->name === 'h1' && $reader->nodeType === XMLReader::ELEMENT) {
echo $reader->readString();
}
}
Run Code Online (Sandbox Code Playgroud)
function getTextBetweenH1($string)
{
$pattern = "/<h1>(.*?)<\/h1>/";
preg_match_all($pattern, $string, $matches);
return ($matches[1]);
}
Run Code Online (Sandbox Code Playgroud)