PHP将数字从字符串中分离成一个数组


PHP separating numbers from string into an array

我正试图将数字从这样的字符串中分离出来:-4-25-30带php

我试过以下几件事:

$fltr = array();
for($i=0;$i<count($q);$i++) {
    $odr = $q[$i]['odr'];
    $fltr = preg_match_all('/([a-z0-9_#-]{4,})/i', $odr, $matches);
}

这个输出:1

以及爆炸功能:

$fltr = array();        
for($i=0;$i<count($q);$i++){
    $odr = $q[$i]['odr'];
    $fltr = explode($odr, '-');
}

注意:$odr包含字符串。

这个给出了O/p:"-"

我想从字符串中取出所有的数字。

试试这个

$fltr = explode('-', trim($odr, '-'));

我认为您在使用explode()时混淆了分隔符和实际字符串。

作为注释,如果您想从字符串中分离所有数字,则需要使用PHPexplode函数。您还需要使用trim从字符串中删除额外的-

$arr = explode('-', trim('-4-25-30', '-'));
print_r($arr); //Array ( [0] => 4 [1] => 25 [2] => 30 )

你也可以这样做,

$arr = array_filter(explode('-', '-4-25-30'));
print_r($arr); //Array ( [0] => 4 [1] => 25 [2] => 30 )

我尝试将上面的所有示例与一些修复结合起来

<?php
$q = array(array('odr' => '-4-25-30'),);
$fltr = array();
for ($i = 0; $i < count($q); $i++)
{
    $odr = $q[$i]['odr'];
    $fltr = preg_match_all('/('d+)/i', $odr, $matches); // find 1 or more digits together
}
echo "attempt 1: 'n";
echo "count: ";
var_export($fltr); // count of items
echo "'nmatches: ";
var_export($matches[0]); // array contains twice the same
echo "'n";
$fltr = array();
for ($i = 0; $i < count($q); $i++)
{
    $odr = $q[$i]['odr'];
    $trim = trim($odr, '-'); // 2nd param is character to be trimed
    $fltr = explode('-', $trim); // 1st param is separator
}
echo "attempt 2, explode: ";
var_export($fltr);
echo "'n";

输出:

attempt 1:
count: 3
matches: array (
  0 => '4',
  1 => '25',
  2 => '30',
)
attempt 2: array (
  0 => '4',
  1 => '25',
  2 => '30',
)
<?php
$odr="-4-25-30";
$str_array=explode("-",trim($odr,"-"));
foreach  ($str_array as $value){
printf("%d'n",$value);
}
?>

应该得到你想要的

要使用preg_match_all函数获得所需的结果,您可以通过以下方法:

$odr = "-4-25-30";
preg_match_all('/[0-9]+?'b/', $odr, $matches);
print_r($matches[0]);

输出:

Array
(
    [0] => 4
    [1] => 25
    [2] => 30
)