【问题标题】:Extract content from HTML comments从 HTML 注释中提取内容
【发布时间】:2021-09-09 07:49:52
【问题描述】:

这是一些 HTML 代码

<!--start--> <h2>some content with any html tag</h2> <!--end-->
<!--start--> </h3> some other content with any html tag </h3><!--end-->

我需要一个 PHP 代码来读取 cmets 数据。棘手的部分是 cmets 是相同的,我需要两个内容。像 H2 和 H3。

我有代码,但它只提供一个。 H3.

$html_file = file_get_contents($allfiles[0]); 

$string = '<!--start-->'.$html_file.'<!--end-->';
preg_match('/<!--start-->(.*)<!--end-->/', $string, $matches);

【问题讨论】:

  • 试试preg_match_all()
  • 它也不起作用。可以请你写一个代码。将不胜感激

标签: php html comments


【解决方案1】:
$html = <<<EOT
<!--start--> <h2>some content with any html tag</h2> <!--end-->
<!--start--> </h3> some other content with any html tag </h3><!--end-->
EOT;
   
// using preg_match_all
preg_match_all('/(<!--start-->)(.*)(<!--end-->)/', $html, $matches1);
$matches = $matches1[2];

foreach ($html of $matches) {
   echo $html;
}

// using explode
$htmla = explode("<!--start-->", $html);
foreach($htmla as $h) $matches2[] = trim(explode("<!--end-->", $h)[0]);
$matches =array_filter($matches2);
print_r($matches2);

例如:https://www.tehplayground.com/ZCxwV8YWCQeePeFF

两种方法都成功:

Array
(
    [1] => <h2>some content with any html tag</h2>
    [2] => </h3> some other content with any html tag </h3>
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 2012-05-20
    • 2021-09-13
    • 2015-08-07
    • 1970-01-01
    • 2012-09-03
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多