将带数字的字符串转换为纯整数


Convert a string with numbers to pure integers

我是一个PHP程序员。我不知道如何将字符串中的数字列表转换为纯整数。

这就是我得到的(!)字符串:

" 70, 51, 53, "

这就是转换后的样子:

70, 51, 53

我想要的是输出:

<? $featureIDs = array(70, 51, 53) ?>

非常感谢您提前提供的帮助!

我不确定示例输入中的引号是否真的是字符串的一部分,但如果是,下面的内容会起作用(它会从输入中去掉任何不是数字或逗号的内容)。

$string = '" 70, 51, 53, "';
$output = explode(',',preg_replace("/[^0-9,]/", "", $string));
foreach($output as $k => $v) {
    if (!$v) {
        unset($output[$k]);
    }
}
var_dump($output);

检查explode()函数:

$numbers = explode(',', '70, 51, 53');

一旦将它们放入数组中,由于PHP是松散类型的,因此可以将它们用作整数或字符串。尾随的,可能会导致问题,因此您可能需要将其删除。

$ a = " 70, 51, 53, ";
$integerArray = explode(',', trim($a , " ," ) ); 

trim()将清除字符串开头和结尾的所有逗号和空格,explose将用逗号分隔字符串,以分隔数组中的字符串,由于php将数字字符串视为数字,因此这是正确的:

$integerArray[0] + 30 == 100

首先:使用删除所有空格

$string = str_replace( ' ', '', $string );

然后,将字符串拆分为每个元素:

$featureIDs = explode( ',', $string );

最后,将所有字符串转换为整数:

array_walk( $featureIDs , 'intval' );

使用preg_match_all(),获取所有"数字序列"。

$input = " 70, 51, 53, ";
$ids = array();
if (preg_match_all('('d+)', $input, $matches)) {
  $ids = $matches[0];
}
var_dump($ids);

输出:

array(3) {
  [0]=>
  string(2) "70"
  [1]=>
  string(2) "51"
  [2]=>
  string(2) "53"
}