使用 PHP 匹配 HTML <p> 标签的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4264678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:27:56  来源:igfitidea点击:

Regular Expression to Match HTML <p> tag using PHP

phpregexpreg-match

提问by Atif Mohammed Ameenuddin

I have some content like this

我有一些这样的内容

<p>some content, paragraph 1</p>
<p>some content, paragraph 2</p>
<p>some content, paragraph 3</p>

I would like to return the first paragraph i.e.

我想返回第一段即

<p>some content, paragraph 1</p>

Can anyone assist me with the regex code?
'<p>(.*.)</p>'doesnt seem to work

任何人都可以帮助我使用正则表达式代码吗?
'<p>(.*.)</p>'似乎不起作用

回答by SubniC

you can do it this way:

你可以这样做:

if (preg_match('%(<p[^>]*>.*?</p>)%i', $subject, $regs)) {
    $result = $regs[1];
} else {
    $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.

你根据正则表达式测试你的字符串,如果有一些匹配,你会得到第一个也是唯一的第一个,如果没有 $result 将是一个空字符串。

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:

如果您需要获得比第一个结果更多的结果,您可以遍历 $regs 数组。并且您需要找到任何其他标签,更改常规表达式以匹配它,例如找到您使用的 IMAGE 标签:

(<img[^>]*>.*?</img>)

EDIT: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, Regards.

HTH,问候。

回答by Fantast

Prevent from include <pre> tag, can use:

防止包含 <pre> 标签,可以使用:

if (preg_match('/(<p(>|\s+[^>]*>).*?<\/p>)/i', $subject, $regs)) {
    $result = $regs[1];
} else {
    $result = "";
}

回答by benhowdle89

  if (preg_match("/\b1\b/i", "some content, paragraph 1")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

Where 1 is the matched term...

其中 1 是匹配项...

Is this is any help?

这有什么帮助吗?