-2

我有 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 和文本都在 AFTER</h1>和 ENDING开始<h2>What we offer</h2> 知道如何在 PHP 中执行此操作吗?

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

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

2 回答 2

1

鉴于您需要的定义,这应该有效:

$beginIndex = strpos($htmlString, "</h1>");
$endIndex = strpos($htmlString, "<h2>What we offer</h2>");
$desiredString = substr($htmlString, $beginIndex, $endIndex - $beginIndex);
于 2012-11-14T14:11:32.087 回答
1

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

$pattern = '/<\/h1>(.*)<h2>What we offer/s';
$matches = array();
preg_match($pattern, $htmlString, $matches);
$desiredString = $matches[1];
于 2012-11-14T14:44:20.747 回答