Rob
Rob

Reputation: 11368

substr_count not working with new lines?

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

Upvotes: 1

Views: 2279

Answers (3)

Jonathan
Jonathan

Reputation: 6732

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"?

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

'\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.

Upvotes: 4

Alix Axel
Alix Axel

Reputation: 154543

You need to use double quotes for control characters:

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

Upvotes: 5

Related Questions