$str = '<p>这是第一个段落。</p><p>这是第二个段落。</p>'; preg_match('/<p>(.*?)</p>/s', $str, $matches); echo $matches[1];
/<p>(.*?)</p>/s
. Among them, /s
means .
means that carriage returns and line feeds can be matched, so paragraphs containing carriage returns and line feeds can be matched. <p>However, the above code can only match the first paragraph. If you want to match all paragraphs, you need to use the preg_match_all function. $str = '<p>这是第一个段落。</p><p>这是第二个段落。</p>'; preg_match_all('/<p>(.*?)</p>/s', $str, $matches); foreach ($matches[1] as $match) { echo $match . '<br>'; }
$matches[1]
array to obtain all matching paragraphs.
<p>So far, we have successfully used PHP regular expressions to match the content of all paragraphs in HTML. However, during the actual development process, it is important to note that HTML may contain some special circumstances, such as nested tags or special characters in paragraphs, which may affect the matching results of regular expressions. Therefore, we need to adjust the regular expression as needed to adapt to different situations of HTML code.
<p>Summary
<p>The process of using PHP regular expressions to match all paragraphs in HTML is as follows:
/<p>(. *?)</p>/s
Matches paragraphs containing the <p>
tag. The above is the detailed content of PHP Regular Expressions: How to match all paragraphs in HTML. For more information, please follow other related articles on the PHP Chinese website!