preg_match_all returns an empty array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • loriann
    New Member
    • Sep 2008
    • 3

    preg_match_all returns an empty array

    hi,

    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):[code=php]
    preg_match ('/<div\s+?id="srN um_\d+?"\s+?cla ss="number">(.* ?)<\/div>/', $page, $results);[/code]

    a sample string which should be matched by the above is:[code=hml]
    <div id="srNum_0" class="number"> 1.</div>[/code]

    Funny that preg_match_all also doesn't work if I give a direct regex to match the line above:[code=php]
    preg_match_all ('/<div id="srNum_0" class="number"> 1\.<\/div>/', $page, $results);[/code]

    On the other hand this one works fine:[code=php]
    preg_match_all ('/<title>(.*?)< \/title>/',$page, $results);[/code]

    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?

    cheers
    Last edited by pbmods; Sep 28 '08, 07:40 PM. Reason: Added CODE tags.
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

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

    This is the code I used:
    [code=php]
    <?php
    $str = ' <div id="srNum_0" class="number"> Contents of the div</div>';
    $regex = '/<div\s+?id="srN um_\d+?"\s+?cla ss="number">(.* ?)<\/div>/';

    if(preg_match_a ll($regex, $str, $patterns))
    {
    echo "Success!\n ". print_r($patter ns, true);
    }
    else
    {
    echo "Failed!";
    }
    ?>
    [/code]
    Which gave me:
    Code:
    Success!
    Array
    (
        [0] => Array
            (
                [0] => 
    Contents of the div
    
            )
    
        [1] => Array
            (
                [0] => Contents of the div
            )
    
    )
    Could it be that your are simply reading the return array incorrectly?

    I'm running PHP 5.2.4 by the way.

    Comment

    • loriann
      New Member
      • Sep 2008
      • 3

      #3
      Hi,

      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.

      cheers

      Comment

      Working...