PHP 遍历一个简单的逗号分隔列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10839147/
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-24 23:11:21  来源:igfitidea点击:

PHP iterating through a simple comma separated list

php

提问by Phil

I have a string which can be

我有一个字符串可以是

$string = "value.";

OR

或者

$string = "value1, value2.";

I want to iterate through this string getting each item which are -> value(in first example) and -> value1AND value2in the second (without the comma or the dot in the end).

我想遍历这个字符串,得到每个项目 -> value(在第一个例子中)和 -> value1ANDvalue2在第二个(最后没有逗号或点)。

I was thinking of;

我在想;

  1. Replace the dot in the end.
  2. Check if there is any comma.
  3. If there is comma, split-explode using ", " and iterate through.
  4. If not, only one item so just use it.
  1. 最后替换点。
  2. 检查是否有逗号。
  3. 如果有逗号,请使用“,”拆分爆炸并迭代。
  4. 如果没有,只有一项,所以只需使用它。

Is this the right way of doing it?

这是正确的做法吗?

I am new to PHP and trying to learn best practices and best ways of solving the issues.

我是 PHP 新手,正在尝试学习最佳实践和解决问题的最佳方法。

Thank you.

谢谢你。

回答by Tyilo

You're absolutely right, you could do it like this:

你是绝对正确的,你可以这样做:

$string = 'foo, bar, baz.';
$string = preg_replace('/\.$/', '', $string); //Remove dot at end if exists
$array = explode(', ', $string); //split string into array seperated by ', '
foreach($array as $value) //loop over values
{
    echo $value . PHP_EOL; //print value
}

回答by sesser

I know this has been answered, but, you could do this with one command:

我知道这已经得到了回答,但是,您可以使用一个命令来做到这一点:

$input = "foo, bar, baz., shibby, poop.";

//-- handles it all in one pass
$output = preg_split('/[\.,\s]/', $input, -1, PREG_SPLIT_NO_EMPTY);

//-- just output
array_walk($output, function(&$item, $idx) {
    echo $idx . ': ' . $item . PHP_EOL;
});

If you're expecting spaces in your values, however, this will split them up too. I just added \sto the regex to trim the elements. If you expect spaces in values, then omit the \sin the regex and trim()the elements later.

但是,如果您希望值中有空格,这也会将它们分开。我只是添加\s到正则表达式来修剪元素。如果您希望值中有空格,则省略\s正则表达式中的 和trim()稍后的元素。

Or, this regex will produce the same: /(\.\s?|,\s?)/

或者,这个正则表达式将产生相同的结果: /(\.\s?|,\s?)/

$input = "foo, bar, baz., shibby, poop. foo bar";

//-- handles it all in one pass
$output = preg_split('/(\.\s?|,\s?)/', $input, -1, PREG_SPLIT_NO_EMPTY);

//-- just output
array_walk($output, function(&$item, $idx) {
    echo $idx . ': ' . $item . PHP_EOL;
});

Produces

生产

0: foo
1: bar
2: baz
3: shibby
4: poop
5: foo bar

The Regex: explained

正则表达式:解释

The original regex simply split on single characters in the string as denoted by the [and ]. Thus, /[\.,\s]/matches on period, comma, AND space characters in the string. After thinking about it, this is probably not what you want but close.

原始正则表达式只是简单地拆分字符串中的单个字符,如[和 所示]。因此,/[\.,\s]/匹配字符串中的句点、逗号和空格字符。仔细想想,这可能不是你想要的,而是关闭的。

The updated regex is a little different and splits on two different scenarios. \.\s?says: split on the period and/or preiod+space. The ?makes the preceding optional (I believe 0 or 1). Same with the ,\s?. Match on comma and/or comma+space. This accounts for all the scenarios. Using grouping ((...)) instead of character ranges allows for this. The pipe |in the middle means OR so, the complete regex means: match on period and/or period+space OR comma and/or comma+space.

更新后的正则表达式略有不同,分为两种不同的场景。\.\s?说:在期间和/或 preiod+space 上拆分。在?使前述可选(I相信0或1)。与,\s?. 匹配逗号和/或逗号+空格。这说明了所有场景。使用分组 ( (...)) 而不是字符范围可以实现这一点。|中间的管道表示 OR 所以,完整的正则表达式表示:匹配句号和/或句号+空格或逗号和/或逗号+空格。

回答by Sandeep Bansal

$string = "value 1, value2";
$string = trim($string, ".");

$split = explode(",", $string);
print_r($split);

回答by Ignacio Vazquez-Abrams

You should not do 2 and 4. If there is no comma then it will split to an array of one element.

你不应该做 2 和 4。如果没有逗号,那么它将拆分为一个元素的数组。

回答by anubhava

I would use following code:

我会使用以下代码:

$string = "value1, value2.";
$arr = explode(', ', trim($string, '.'));
print_r($arr);

OUTPUT

输出

Array
(
    [0] => value1
    [1] => value2
)

回答by MetalFrog

When you explode, and there is no delimiter you have requested, the result at index 0 is the entire string.

当您爆炸时,并且没有您请求的分隔符,索引 0 处的结果是整个字符串。

<?php
$string = "test, test2., test3, test4";
print_r( explode(',', $string) );
//Array
//(
//    [0] => test
//    [1] =>  test2.
//    [2] =>  test3
//    [3] =>  test4
//)

$string = "test test2. test3 test4";
print_r( explode(',', $string) );
//Array
//(
//    [0] => test test2. test3 test4
//)

回答by Mosin

try this code

试试这个代码

$arr="a,b,c";
$variableAry=explode(",",$arr); 
foreach($variableAry as $var)
{
 echo"<input type='text' value=".$var." ><br/><br/>";
}