[英]Converting comma-separated string of single-quoted numbers to int array
I have a string:我有一个字符串:
'24','27','38'
I want to convert it:我想转换它:
(
[0] => 24
[1] => 27
[2] => 38
)
The conversion: https://3v4l.org/oDPDl转换: https : //3v4l.org/oDPDl
array_map('intval', explode(',', $string))
gives:给出:
Array
(
[0] => 0
[1] => 0
[2] => 0
)
Basically, array_map()
works when the numbers aren't quoted like `24,27,38', but I need a technique that works with quoted numbers.基本上,
array_map()
在数字没有像‘24,27,38’那样被引用时起作用,但我需要一种处理引用数字的技术。
One solution is looping over the array, but I don't want to do that.一种解决方案是遍历数组,但我不想这样做。 Can I achieve the above using only php functions (not control structures -- eg
foreach()
)?我可以仅使用 php 函数(不是 控制结构——例如
foreach()
)来实现上述目标吗?
Use the following approach: 使用以下方法:
$str = "'24','27','38'";
$result = array_map(function($v){ return (int) trim($v, "'"); }, explode(",", $str));
var_dump($result);
The output: 输出:
array(3) {
[0]=>
int(24)
[1]=>
int(27)
[2]=>
int(38)
}
$arr = explode (",", str_replace("'", "", $str));
foreach ($arr as $elem)
$array[] = trim($elem) ;
Without looping:不循环:
$str= "'24','27','38'";
$arr = array_map("intval", explode(",", str_replace("'", "", $str)));
var_dump($arr); var_dump($arr);
Output:输出:
array(3) {
[0]=>
int(24)
[1]=>
int(27)
[2]=>
int(38)
}
sscanf()
can instantly return type-cast values if you ask it to.如果您要求,
sscanf()
可以立即返回类型转换值。
Here is a technique that doesn't use an explicit loop: sscanf(preg_replace())
这是一种不使用显式循环的技术:
sscanf(preg_replace())
var_export(sscanf($string, preg_replace('/\d+/', '%d', $string)));
Output:输出:
array (
0 => 24,
1 => 27,
2 => 38,
)
Or some developers might find this more professional/intuitive (other will disagree): ( Demo )或者一些开发人员可能会发现这更专业/直观(其他人会不同意):(演示)
var_export(filter_var_array(explode("','", trim($string, "'")), FILTER_VALIDATE_INT));
// same output as above
or perhaps this alternative which leverages more commonly used native functions:或者这个替代方案利用了更常用的本机功能:
var_export(
array_map(
function($v) {
return (int)$v;
},
explode("','", trim($string, "'"))
)
);
which simplifies to:简化为:
var_export(array_map('intval', explode("','", trim($string, "'"))));
// same output as above
For anyone who doesn't care about the datatype of the newly generated elements in the output array, here are a few working techniques that return string elements: ( Demo )对于不关心输出数组中新生成元素的数据类型的任何人,这里有一些返回字符串元素的工作技术:( Demo )
var_export(explode("','", trim($string, "'")));
var_export(preg_split('/\D+/', $string, -1, PREG_SPLIT_NO_EMPTY));
var_export(preg_match_all('/\d+/', $string, $m) ? $m[0] : []);
var_export(filter_var_array(explode(',', $string), FILTER_SANITIZE_NUMBER_INT));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.