PHP preg_match returns null. Why?

The following preg_match call returns null within a WordPress code:

preg_match('/(<div class="title-primary">)([^<]*)(</div>)/', $content, &$matches)

Even if the input contains: <div class="title-primary"> bla-bla </div>.

Read More

There are no PHP errors.

This works well when tested with online tools:

Result:

Array
(
    [0] => <div class="title-primary">
                     bla-bla            </div>
    [1] => <div class="title-primary">
    [2] =>
                     bla-bla
    [3] => </div>
)

Any idea what might be the problem?

Related posts

1 comment

  1. This indeed works well when testing with online tools or my own environment. Submitted at http://phptester.net/

    <?php
    $content = '<div class="title-primary"> bla-bla </div>';
    
    preg_match('/(<div class="title-primary">)([^<]*)(</div>)/', $content, &$matches);
    
    print_r($matches);
    

    Result:

    Array ( [0] =>
    bla-bla
    [1] =>
    [2] => bla-bla [3] =>
    ) 
    

    Which means that it must be something else in your code that prevents this from running properly. First thing that I would look at would be why you are using pass-by-reference operator with $matches – is there a chance that $matches gets over-written somewhere in between the preg_match and the point at which you are debugging the code?

Comments are closed.