正则表达式以匹配HTML< p>使用PHP标记 [英] Regular Expression to Match HTML <p> tag using PHP
问题描述
我有一些类似的内容
<p>some content, paragraph 1</p>
<p>some content, paragraph 2</p>
<p>some content, paragraph 3</p>
我想返回第一段,即
<p>some content, paragraph 1</p>
有人可以用正则表达式代码帮助我吗?
'<p>(.*.)</p>'
似乎不起作用
Can anyone assist me with the regex code?
'<p>(.*.)</p>'
doesnt seem to work
推荐答案
您可以这样操作:
if (preg_match('%(<p[^>]*>.*?</p>)%i', $subject, $regs)) {
$result = $regs[1];
} else {
$result = "";
}
您将字符串与常规表达式进行比较,如果有匹配项,则得到第一个,只有第一个,如果没有匹配项,则$ result将为空字符串.
You test your string against the regular expresion, if there are some match, you get the first and only the first one, if there are none $result will be an empty string.
如果您需要获得比第一个结果更多的结果,则可以遍历$ regs数组.并且您需要找到其他任何标签,将常规expresión更改为该标签,例如查找您使用的IMAGE标签:
If you need to get more than the first result you can iterate over the $regs array. And of you need to find any other tag change the regular expresión to macht it, for example to find IMAGE tags you use:
(<img[^>]*>.*?</img>)
编辑:如果您要逐行处理(仅包含您要查找的标记),则可以在表达式周围加上^ ... $以匹配整行,如下所示:
If you are processing line by line (with only the tag you are looking for) you can put ^...$ around the expresion to match a full line, like this:
if (preg_match('%^(<p[^>]*>.*?</p>)$%im', $subject, $regs)) {
$result = $regs[1];
} else {
$result = "";
}
HTH,致谢.
这篇关于正则表达式以匹配HTML< p>使用PHP标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!