问题
If I have a piece of code that works like this:
$i = 0;
$names = explode(",", $userInput);
foreach($names as $name) {
$i++;
}
It works perfectly, provided the user has placed a comma after each name entered into the html textarea this comes from. But I want to make it more user friendly and change it so that each name can be entered on a new line and it'll count how many lines the user has entered to determine the number of names entered into the field. So I tried:
$i = 0;
$names = explode("\n", $userInput);
foreach($names as $name) {
$i++;
}
But this just gives me "1" as a result, regardless the number of new lines in the textarea. How do I make my explode count new lines instead of basing the count on something specifically entered into the text string?
EDIT Thanks to the people who answered, I don't believe there were any wrong answers as such, just one that suited my original code better than the others, and functioned. I ended up adopting this and modifying it so that numerous blank line returns did not result in artificially inflating the $userInput count. Here is what I am now using:
if(($userInput) != NULL) {
$i = 0;
$names = explode(PHP_EOL, trim($userInput));
foreach($names as $name) {
$i++;
}
}
It trims the empty space from the $userInput so that the remainder of the function is performed on only valid line content. :)
回答1:
Try using the PHP end of line constant PHP_EOL
$names = explode(PHP_EOL, $userInput);
回答2:
Don't make it complicated, you don't have to explode it into an array, just use this:
(Just count the new line character (PHP_EOL) in your string with substr_count())
echo substr_count($userInput, PHP_EOL);
回答3:
A blank string as input:
var_dump(explode("\n", ''));
gives this as a result from a call to explode():
array(1) { [0]=> string(0) "" }
so you could use a ternary statement:
$names = $userInput == '' ? array() : explode("\n", $userInput);
回答4:
Maybe you can change the explode function with preg_split to explode the user string with a regex
$users = preg_split('/[\n\r]+/', $original);
That's the idea, but I'm not on the computer so I can't test my code. That regex would split the string if it founds one or more line breaks.
来源:https://stackoverflow.com/questions/29589767/php-foreach-counting-new-lines-n