By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,664 Members | 1,623 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,664 IT Pros & Developers. It's quick & easy.

preg_match_all returns an empty array

P: 3

I have a problem with preg_match function returning empty arrays for my wonderful regexes. However, I can't see what I am doing wrong - maybe one of you could help?

I'm loading the source of a website into variable and then using preg_match_all to extract all occurrences of a string.

it looks like this (where source code is loaded into $page variable):
Expand|Select|Wrap|Line Numbers
  1. preg_match ('/<div\s+?id="srNum_\d+?"\s+?class="number">(.*?)<\/div>/', $page, $results);
a sample string which should be matched by the above is:
Expand|Select|Wrap|Line Numbers
  1. <div id="srNum_0" class="number">1.</div>
Funny that preg_match_all also doesn't work if I give a direct regex to match the line above:
Expand|Select|Wrap|Line Numbers
  1. preg_match_all ('/<div id="srNum_0" class="number">1\.<\/div>/', $page, $results);
On the other hand this one works fine:
Expand|Select|Wrap|Line Numbers
  1. preg_match_all ('/<title>(.*?)<\/title>/',$page, $results);
Tried hard to find the answer, to add backslashes, change single quotes to double quotes etc.
Can you see a mistake? Should any characters be escaped?

Sep 28 '08 #1
Share this Question
Share on Google+
2 Replies

Expert 5K+
P: 5,058

I tried your regular expression and it worked fine on my test server.

This is the code I used:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $str = ' <div id="srNum_0" class="number">Contents of the div</div>';
  3. $regex = '/<div\s+?id="srNum_\d+?"\s+?class="number">(.*?)<\/div>/';
  5. if(preg_match_all($regex, $str, $patterns))
  6. {
  7.     echo "Success!\n". print_r($patterns, true);
  8. }
  9. else
  10. {
  11.     echo "Failed!";
  12. }
  13. ?>
Which gave me:
Expand|Select|Wrap|Line Numbers
  1. Success!
  2. Array
  3. (
  4.     [0] => Array
  5.         (
  6.             [0] => 
  7. Contents of the div
  9.         )
  11.     [1] => Array
  12.         (
  13.             [0] => Contents of the div
  14.         )
  16. )
Could it be that your are simply reading the return array incorrectly?

I'm running PHP 5.2.4 by the way.
Sep 29 '08 #2

P: 3

thank you for your reply.
It turns out that the problem was not actually the regexps itself. As you said this should be working I started to look for a problem elsewhere. It looks that the page content wasn't loaded properly into the variable - now it's sorted out and regexes are returning what they are supposed to.

Thank you for help.

Oct 1 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.