开发者

How to regex match text with different endings?

This is what I have at the moment.

<h2>Information</h2>\n  +<p>(.*)<br />|</p>
                  ^ that is a tab space, didn't know if there was
 a better way to represent one or more (it seems to work)

Im trying to match the 'bla bla.' text, but my current regex doesn't quite work, it will match most of the line, but I want it to match the first

<h2>Information</h2>
    <p>bla bla.<br /><br /><a href="http://www.google.com">google开发者_运维知识库</a><br />

or

<h2>Information</h2>
    <p>bla bla.</p> other code...

Oh and my php code:

    preg_match('#h2>Information</h2>\n  +<p>(.*)<br />|</p>#', $result, $postMessage);                          


Don't use regex to parse HTML. PHP provides DOMDocument that can be used for this purpose.

Having said that you have some errors in your regular expression:

  • You need parentheses around the alternation.
  • You need lazy modifiers.
  • You can't type 'header' to match 'Information'.

With these changes it would look like this:

<h2>.*?</h2>\n\t+<p>.*?(<br />|</p>)

Your regular expression is also very fragile. For example, if the input contains spaces instead of tabs or the line ending is Windows-style, your regular expression will fail. Using a proper HTML parser will give a much more robust solution.


Use \s to match any whitespace character (including spaces, tabs, new-line feeds, etc.), e.g.

preg_match('#<h2>header</h2>\s*<p>(.*)<br />|</p>#', $result, $postMessage);  

But, as already mentioned, do not use regular expressions to parse HTML.


the .* match should be non greedy (match the minimum of arbitrary characters instead of the maxium), that is (.*?) i guess in PHP.


Try making your match non-greedy by using (.*?) in place of (.*)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜