1

This is driving me nuts, it keeps returning 0

substr_count('df
d
fd
f
df', '\n');

if I use a letter like "d", it works fine

substr_count('df
d
fd
f
df', 'd');

Can anyone shed some light on this?

Thanks

Rob
  • 10,851
  • 21
  • 69
  • 109

3 Answers3

5

You need to use double quotes for control characters:

var_dump(substr_count('df
d
fd
f
df', "\n"));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
4

'\n' is not the same as "\n". '\n' is text comprising a slash and the letter "n", whereas "\n" is a newline character.

Suggest you read the relevant section of the PHP manual about strings, particularly where it talks about single and double quoted strings.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

In addition to Alix and Mark: please use PHP_EOL instead of \n. Newlines differ on the different platforms (Windows/Linux/Mac), but PHP_EOL is always right. See this question for more info on the subject: When do I use the PHP constant "PHP_EOL"?

Community
  • 1
  • 1
Jonathan
  • 6,572
  • 1
  • 30
  • 46
  • 1
    Humm... I would argue that `\n` is safer in general because it's present in both `\n` and `\r\n`, the exception would be `\r` (old Mac). If the input string comes from a *nix system (`\n`) and the server runs on Windows (`\r\n`), `PHP_EOL` will not work. To be on the safe side, I always normalize newlines to `\n` with the following regex: `$str = preg_replace('~\r\n?~', "\n", $str);`. – Alix Axel Apr 28 '12 at 22:18
  • @AlixAxel Hmm, seems true for input, according to this answer: http://stackoverflow.com/a/4975441/251760 Didn't knew that, thanks for your comment! – Jonathan Apr 28 '12 at 22:21