Jacob
Jacob

Reputation: 2071

Can't get regex to work. Empty returns

I've tried this regex on three different "regex generators" online. It works fine. But when I run it on my local machine I get empty arrays as response.

This is my code.

$string = "Testing \$test;";
preg_match_all("/(\$[A-Za-z]*)/", $string, $match);
print_r($match);

Response is:

Array
(
    [0] => Array
        (
            [0] => 
        )

    [1] => Array
        (
            [0] => 
        )

)

I've tried http://regexr.com/, https://regex101.com/#pcre, http://www.phpliveregex.com/ All work fine.

What is going on? Why is preg_match_all returning empty values on my machine? How can I debug this?

Thanks in advance

Upvotes: 0

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

Because you used a double quoted string literal, you need to double backslashes:

preg_match_all("/(\\$[A-Za-z]*)/", $string, $match);

See the IDEONE demo

Otherwise, the $ with characters after it is parsed as a variable to expand.

That is why in most cases, a single quoted literal is preferred (demo) (as no variable expansion is expected inside it):

preg_match_all('/(\$[A-Za-z]*)/', $string, $match);

Upvotes: 4

Related Questions