0

I'm looking at a regular expression to match any characters. I know that the '.' is a placeholder except for newline. Given this code below:

$fruits = "One\nTwo\nThree";
preg_match_all('/^(.*)$/', $str, $matches);
print_r($matches);

Why does it not match anything at all? I would think, $matches[0] would be One Two Three?

2
  • Odd. Your code works for me. Commented Nov 11, 2012 at 23:39
  • It works just fine: rubular.com/r/is69Ug3qNN Look at the @irrelephant comment! Commented Nov 11, 2012 at 23:44

1 Answer 1

2

Add the modifier "s" to the regex:

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

$fruits = "One\nTwo\nThree";
preg_match_all('/^(.*)$/s', $fruits, $matches);
print_r($matches);

Update:

If you enclose $fruits in single quotes, the newline isn't treated as such and the replacement also works, event without the "s" modifier. But I don't know if the output is what you expect it to be ;)

   $fruits = 'One\nTwo\nThree';
   preg_match_all('/^(.*)$/', $fruits, $matches);
   print_r($matches);
Sign up to request clarification or add additional context in comments.

1 Comment

Also, if your regex engine doesn't support the s modifier or similar, or you only want its behaviour in one area, you can use [\s\S].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.