php - 使用 PHP 的 preg_replace() 只返回 <h1>?

标签 php html regex preg-replace

我将如何使用 PHP 的 preg_replace()只返回 <h1> 中的值在以下字符串中(它是加载到名为 $html 的变量中的 HTML 文本):

<h1>I'm Header</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis.</p>

<p>Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

我试过这个:preg_replace('#<h1>([.*])</h1>.*#', '$1', $html) ,但无济于事。我正则表达式正确吗?是否有更好的 PHP 函数我应该使用而不是 preg_replace

最佳答案

下面是使用 preg_replace 的方法:

$header = preg_replace('/<h1>(.*)<\/h1>.*/iU', '$1', $html);

你也可以使用preg_match:

$matches = array();
preg_match('/<h1>(.*)</h1>.*/iU', $html, $matches);
print_r($matches);

关于php - 使用 PHP 的 preg_replace() 只返回 <h1>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970112/

相关文章:

javascript - javascript 中的正则表达式只允许数字、逗号和一个小数点

php - 如果我只执行一个查询,那么使用事务的好处是否足够重要?

php - 通过引用传递键和值的替代方法 :

javascript - 为什么我的 vue.js 按钮不创建新的文本区域?

html - 由于无滚动滚动条,Div 不是全宽/全高?

html - 垂直对齐 h1 并保持宽度为 100%

java - 在忽略大小写的情况下使用正则表达式匹配字符串

regex - 将不同的正则表达式可能性合并为一个

php - 可以在 PHP 中将闭包传递给 usort 吗?

php - 将 $_SESSION ['somthing' ] 分配给变量时未定义索引