Usin Preg_match_all with "\" character

50 views Asked by At

I am trying to get a expression from a string using preg_match_all

but it doesn´t work correctly I try this:

$string='this is a test hello \1234';
preg_match_all('[(\\)(0-9)], $string, $output);

It only shows "hello" if I quit the "\" of the $string I can see "hello 1234" but with "\" It doesn´t works.

2

There are 2 answers

0
flynorc On BEST ANSWER

i think i might have a solution for you

$string='this is a test hello \1234';
preg_match("/hello \\\\[0-9]*/", $string, $output);
var_dump($output);

the thing here are the 4 backslashes. I'm not 100% sure about this but i think it is because in php you need to escape backslash so \\ produces \ and in the regular expression you need two backslashes as well (see praveen kumars answer for a good regexp explanation). So when you are using 4 backslashes, php changes that to 2 and that is what you need for this regexp

EDIT: turns out there was some truth in my thoughts. check out this article for more explanation

1
Praveen Kumar Purushothaman On

If you use something like this:

/^(hello \\[0-9]*)$/g

This will give you the whole one. See the ( and [ variations.

Explanation

explanation