[英]Simple question, comma delimited id's to array in php 5.2
I've got a comma delimited string of id's coming in and I need some quick way to split them into an array. 我有一个以逗号分隔的id字符串,我需要一些快速的方法将它们分成一个数组。 I know that I could hardcode it, but that's just gross and pointless.
我知道我可以对其进行硬编码,但这只是粗略而毫无意义的。
I know nothing about regex at all and I can't find a SIMPLE example anywhere on the internet, only huge tutorials trying to teach me how to master regular expressions in 2 hours or something. 我对正则表达式一无所知,并且在互联网上任何地方都找不到简单的示例,只有大量的教程试图教我如何在2小时之内掌握正则表达式。
fgetcsv is only applicable for a file and str_getcsv is only available in PHP 5.3 and greater. fgetcsv仅适用于文件,str_getcsv仅在PHP 5.3及更高版本中可用。
So, am I going to have to write this by hand or is there something out there that will do it for me? 因此,我是否必须手动编写此文件,或者是否有适合我的东西? I would prefer a simple regex solution with a little explanation as to why it does what it does.
我希望有一个简单的正则表达式解决方案,并对其原因进行解释。
Any problem with normal split function? 正常的分割功能有问题吗?
$array = split(',', 'One,Two,Three');
will give you 会给你
Array
(
[0] => One
[1] => Two
[2] => Three
)
一个简单的正则表达式就可以解决问题。
$a_ids = preg_split('%,%', $ids);
If you want to just split on commas: 如果只想分割逗号:
$values = explode(",", $string);
If you also want to get rid of whitespace around the commas (eg: your string is 1, 3, 5
) 如果您还想摆脱逗号周围的空格(例如:您的字符串为
1, 3, 5
)
$values = preg_split('/\s*,\s*/', $string)
If you want to be able to have commas in your string when surrounded by quotes, (eg: first, "se,cond", third
) 如果希望在字符串中用引号引起来逗号,例如(例如:
first, "se,cond", third
)
$regex = <<<ENDOFREGEX
/ " ( (?:[^"\\\\]++|\\\\.)*+ ) \"
| ' ( (?:[^'\\\\]++|\\\\.)*+ ) \'
| ,+
/x
ENDOFREGEX;
$values = preg_split($regex, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.