【问题标题】:How to stop adding new values to an array after one value is added to that array?将一个值添加到该数组后如何停止向该数组添加新值?
【发布时间】:2017-11-30 18:00:11
【问题描述】:

我有一些 html 文件包含相同的标签,这些标签之间有不同的字符串,我想从特定标签中获取字符串,在它找到第一个匹配项之后,这个字符串是唯一添加到数组中的,有关更多详细信息,请参阅这段代码。

html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1>Some Text</h1>
    <p>This is the first Paragraph</p>
    <ul>
      <li></li>
      <li></l1>
    </ul>
    <p>This is the second Pharagraph</p>
  </body>
</html>

html 文件将包含更多元素

我只想获取第一个 &lt;p&gt; 中的文本,并防止浪费时间搜索整个 html 文件,而我只想从特定标签中获取一个值。

PHP:

//Loop inside all the HTML files inside a folder
$files = glob("files/*.html");
foreach($files as $file){ 
    //Get the whole content of each HTMl file
    $content = file_get_contents($file);
    //Search for specific tag
    preg_match_all('#<p>(.*?)<\/p>', $content, $matches);
}

我只想将第一个匹配项的值添加到$matches

我无法编辑 html 代码以将 class 或 id 添加到我想从中获取值的标签,因为我不是创建它们的人,我无法手动编辑所有文件强>

我不介意使用其他方式来获取这些值,但它应该可以达到我想要的效果(只有第一个匹配项,然后停止搜索整个文件)

【问题讨论】:

标签: php arrays regex html


【解决方案1】:

您可以使用DomDocument 来做到这一点。

<?php 
$html = '<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1>Some Text</h1>
    <p>This is the first Paragraph</p>
    <ul>
      <li></li>
      <li></l1>
    </ul>
    <p>This is the second Pharagraph</p>
  </body>
</html>';

$err = libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
libxml_clear_errors();
libxml_use_internal_errors($err);

// find all p tags, select the first, get its value
$pValue = $dom->getElementsByTagName('p')->item(0)->nodeValue;

//This is the first Paragraph
echo $pValue;

https://3v4l.org/kjFoC

所以如果你想添加到你的代码中,也许可以这样做:

<?php 
function getFirstParagraph($src) {
    $err = libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML($src);
    libxml_clear_errors();
    libxml_use_internal_errors($err);

    return $dom->getElementsByTagName('p')->item(0)->nodeValue;
}

//Loop inside all the HTML files inside a folder
$files = glob("files/*.html");
foreach($files as $file){ 
    //Get the whole content of each HTMl file
    $content = file_get_contents($file);
    //
    $matches[] = getFirstParagraph($content);
}

【讨论】:

  • 谢谢你的回答,是搜索整个html代码然后打印第一个还是找到第一个匹配后停止?
  • 查看代码,找到所有p标签,选择第一个并获取它的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 2018-06-07
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多