substr_count not working with new lines?

2019-08-01 20:14发布

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

3条回答
孤傲高冷的网名
2楼-- · 2019-08-01 20:39

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

查看更多
smile是对你的礼貌
3楼-- · 2019-08-01 20:51

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

查看更多
Ridiculous、
4楼-- · 2019-08-01 21:00

You need to use double quotes for control characters:

var_dump(substr_count('df
d
fd
f
df', "\n"));
查看更多
登录 后发表回答