Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - Regular Expression to Match HTML <p> tag using PHP

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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>)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...