【问题标题】:PHP regular expression, get data partPHP正则表达式,获取数据部分
【发布时间】:2012-11-14 13:53:01
【问题描述】:

我有 HTML 数据,但我想获取这些数据的一部分。顶部和底部应删除。 (H1 之后和 H2 之上的所有内容都应该放在一个变量中)

<p>This text can be deleted</p>
<h1>This title also</h1>

<h2>FROM THIS TITLE I WANT THE TEXT</h2><p>SAME HERE</p>
<h2>...</h2><p>...</p>

<h2>What we offer</h2>
<p>This text isn't needed</p>

我希望所有 HTML 和文本在 &lt;/h1&gt; 之后开始并在 &lt;h2&gt;What we offer&lt;/h2&gt; 结束 知道如何在 PHP 中执行此操作吗?

这在没有正则表达式的情况下可以解决问题(感谢 Alexandru),但我很好奇我可以使用什么正则表达式来实现这一点......

$beginIndex = strpos($htmlString, "</h1>");
$endIndex = strpos($htmlString, "<h2>What we offer</h2>");
$desiredString = substr($htmlString, $beginIndex, $endIndex - $beginIndex);

【问题讨论】:

标签: php html regex


【解决方案1】:

您请求的正则表达式解决方案如下所示:

$pattern = '/<\/h1>(.*)<h2>What we offer/s';
$matches = array();
preg_match($pattern, $htmlString, $matches);
$desiredString = $matches[1];

【讨论】:

  • 太好了,没想到答案这么简单:o
【解决方案2】:

根据您需要的定义,这应该可以工作:

$beginIndex = strpos($htmlString, "</h1>");
$endIndex = strpos($htmlString, "<h2>What we offer</h2>");
$desiredString = substr($htmlString, $beginIndex, $endIndex - $beginIndex);

【讨论】:

  • 这确实有效。但我很好奇正则表达式也会这样做......很难理解正则表达式,这将是一个理想的例子;)
猜你喜欢
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多