php 用每个空格拆分PHP中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5020202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:33:21  来源:igfitidea点击:

Splitting up a string in PHP with every blank space

phpstring

提问by AKor

I have an input where a user may type in multiple words, and they are told to separate it with a space. So input may look like this:

我有一个用户可以输入多个单词的输入,他们被告知用空格分隔。所以输入可能是这样的:

foo

or like this:

或者像这样:

foo bar php js

How can I check for spaces, and if there are spaces, split the words, then put it all into an array? I'll loop through that array in my program. I'm just new to string handling like this.

如何检查空格,如果有空格,将单词拆分,然后将其全部放入数组中?我将在我的程序中遍历该数组。我只是这样处理字符串的新手。

回答by Daniel A. White

See explode

explode

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

回答by enam

Yes explodewill do every thing for you and foreachcan be used to retrieve the values from the array again. Your complete code will be something like following one:

是的,explode会为你做每件事,foreach可用于再次从数组中检索值。您的完整代码将类似于以下代码:

$str = "foo bar php js";
$arr =  explode(" ", $str);

//print all the value which are in the array
foreach($arr as $v){
    echo $v;
}

Hope this will help you.

希望这会帮助你。

回答by Mr Coder

Daniel has already posted about the splitting part, let me add the checking for space part also.

Daniel 已经发布了关于拆分部分的信息,让我也添加检查空间部分。

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pizza = trim($pizza);

if(strpos($pizza, " ") !== false)

    $pieces = explode(" ", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2

}else{

    echo $pizza;

}

回答by mickmackusa

Your sample input is relatively calm. If you are trusting your users to perfectly enter qualifying substrings which are always delimited by exactly one space, then the best choice is explode().

您的样本输入相对平静。如果您相信您的用户能够完美地输入始终由一个空格分隔的合格子字符串,那么最好的选择是explode().

If the user input can vary beyond just lowercase letters or you want to validate while extracting, there are other more appropriate functions to call.

如果用户输入的变化不仅仅是小写字母,或者您想在提取时进行验证,则可以调用其他更合适的函数。

Understanding you business logic will determine the best solution for this task.

了解您的业务逻辑将决定此任务的最佳解决方案。

A demonstration: https://3v4l.org/3TT2V

演示:https: //3v4l.org/3TT2V

$input = "foo bar, php js  double-space apo'strophe 9 ";

echo 'explode(): '; var_export(explode(' ', $input));

echo "\npreg_split(): "; var_export(preg_split('/ +/', $input, null, PREG_SPLIT_NO_EMPTY));

echo "\nstr_word_count(): "; var_export(str_word_count($input, 1));

echo "\npreg_match_all(): "; var_export(preg_match_all('/[a-z]+/', $input, $output) ? $output[0]: []);

Output:

输出:

explode(): array (
  0 => 'foo',
  1 => 'bar,',
  2 => 'php',
  3 => 'js',
  4 => '',
  5 => 'double-space',
  6 => 'apo\'strophe',
  7 => '9',
  8 => '',
)
preg_split(): array (
  0 => 'foo',
  1 => 'bar,',
  2 => 'php',
  3 => 'js',
  4 => 'double-space',
  5 => 'apo\'strophe',
  6 => '9',
)
str_word_count(): array (
  0 => 'foo',
  1 => 'bar',
  2 => 'php',
  3 => 'js',
  4 => 'double-space',
  5 => 'apo\'strophe',
)
preg_match_all(): array (
  0 => 'foo',
  1 => 'bar',
  2 => 'php',
  3 => 'js',
  4 => 'double',
  5 => 'space',
  6 => 'apo',
  7 => 'strophe',
)

回答by Endophage

As Daniel said, explode()is perfect for this kind of situation. You may also want to look at preg_split()(purely for future reference) as it accepts a regex rather than just a simple delimiter and will allow you to break up input on a more complex pattern.

正如丹尼尔所说,explode()非常适合这种情况。您可能还想查看preg_split()(仅供将来参考),因为它接受正则表达式而不仅仅是一个简单的分隔符,并且允许您将输入分解为更复杂的模式。

回答by Jemuel Elimanco

For optimization purposes, i think its better to remove excess spaces like double spaces before using explode function. for example: if you have "foo bar php js "this string must become "foo bar php js"before using explode function. you may try this code:

出于优化目的,我认为最好在使用爆炸功能之前删除双倍空格等多余空格。例如:如果你有"foo bar php js "这个字符串必须"foo bar php js"在使用explode函数之前变成。你可以试试这个代码:

$charSet = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $charSet);
$charSet = rtrim($charSet);
$charSetArray = explode(" ", $charSet);
echo $charSetArray[0];
echo $charSetArray[1];

回答by Shahzad Ahmed

This will work if there is no space between the input string.`

如果输入字符串之间没有空格,这将起作用。`

    $pieces = explode(" ", $pizza);
    if(count($pieces > 1)) {
        foreach($pieces as $piece) {
            echo $piece;
        }
    }
    else {
        echo $userInput;
    }
?>`

Explanation :
After exploding the string into pieces. Firstly it checks if we have more items in array i.e. $piecesif yes it will print via foreachloop otherwise it will simply print the user input.

解释:
将绳子炸成碎片后。首先,它检查数组中是否有更多项目,即$pieces如果是,它将通过foreach循环打印,否则它将简单地打印用户输入。