在 php 中将字符串中的特殊字符与数字分开
separate special characters from numbers in string in php
我在字符串中有 $value = "10,120,152"
,现在我想将每个数字放在单独的变量中,例如 $a = 10; $b = 120; $c = 152;
所以基本上我要问的是如何将 ,
与字符串中的数字分开。
$exploded = explode("," , $values);
var_dump($exploded);
您可以使用 explode(),它将 return 一个包含数字的数组。
$array = explode(',', $value);
使用 list
检查这个
$value = "10,120,152";
$variables = explode("," , $values);
$variables = array_map('intval', $variables);//If you want integers add this line
list($a, $b, $c) = $variables;
如果分隔符始终是 ,
,那么使用 explode 更有意义。如果分隔符不同,您可以使用正则表达式。
$value = "10,120,152";
preg_match_all('/(\d+)/', $value, $matches);
print_r($matches[1]);
输出:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
那个\d+
都是连续数
Regex101 演示:https://regex101.com/r/rP2bV1/1
第三种方法是使用 str_getcsv。
$value = "10,120,152";
$numbers = str_getcsv($value, ',');
print_r($numbers);
输出:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
我在字符串中有 $value = "10,120,152"
,现在我想将每个数字放在单独的变量中,例如 $a = 10; $b = 120; $c = 152;
所以基本上我要问的是如何将 ,
与字符串中的数字分开。
$exploded = explode("," , $values);
var_dump($exploded);
您可以使用 explode(),它将 return 一个包含数字的数组。
$array = explode(',', $value);
使用 list
检查这个$value = "10,120,152";
$variables = explode("," , $values);
$variables = array_map('intval', $variables);//If you want integers add this line
list($a, $b, $c) = $variables;
如果分隔符始终是 ,
,那么使用 explode 更有意义。如果分隔符不同,您可以使用正则表达式。
$value = "10,120,152";
preg_match_all('/(\d+)/', $value, $matches);
print_r($matches[1]);
输出:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
那个\d+
都是连续数
Regex101 演示:https://regex101.com/r/rP2bV1/1
第三种方法是使用 str_getcsv。
$value = "10,120,152";
$numbers = str_getcsv($value, ',');
print_r($numbers);
输出:
Array
(
[0] => 10
[1] => 120
[2] => 152
)