php foreach计算新行(\ n) [英] php foreach counting new lines (\n)

查看:43
本文介绍了php foreach计算新行(\ n)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一段像这样的代码:

If I have a piece of code that works like this:

$i = 0;
$names = explode(",", $userInput);
foreach($names as $name) {
    $i++;
}

如果用户在此名称来源的html文本区域中输入的每个名称之后都放置了逗号,则它可以完美地工作.但是我想使其更加用户友好并进行更改,以便可以在新行中输入每个名称,并且它将计算用户已输入的行数,以确定在该字段中输入的名称数.所以我尝试了:

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++;
}

但是,无论文本区域中新行的数量如何,这只会给我"1"的结果.如何使爆炸计数新行而不是将计数基于专门输入到文本字符串中的内容?

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?

编辑多亏了回答的人,我不认为会有任何错误的答案,只是一个比我的原始代码更适合我的原始代码并且可以正常工作的答案.我最终采用并对其进行了修改,以使大量空白行返回不会导致人为地增加$ userInput计数.这是我现在正在使用的:

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++;
        }
    }

它会修剪$ userInput中的空白区域,以便仅在有效的行内容上执行该函数的其余部分.:)

It trims the empty space from the $userInput so that the remainder of the function is performed on only valid line content. :)

推荐答案

尝试使用PHP行尾常量PHP_EOL

Try using the PHP end of line constant PHP_EOL

$names = explode(PHP_EOL, $userInput);

这篇关于php foreach计算新行(\ n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆