tags:

views:

51

answers:

4

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"&gt;google&lt;/a&gt;&lt;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);                          
+1  A: 

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

amic
+1  A: 

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

codaddict
+6  A: 

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.

Mark Byers
+1 for don't use regex. See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags for further details.
Török Gábor
Cheers, and I will look into that DOMDocument as I can't say I like using regex, it was just all I knew that cold do it.
Mint
Oops, that header thing was a typo.
Mint
It's ridiculous how many times this needs to be restated. This same question pops up almost daily.
Keith Rousseau
+2  A: 

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.

Felix Kling
Ah yeah, might use \s then. Will definitely read up on this DOMDocument thingy that PHP provide.
Mint