PHP分离串号到数组

问题描述:

我想从这样的字符串分隔的数字: -4-25-30用PHPPHP分离串号到数组

我曾尝试以下操作:

$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:“ - ”

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

+1

这可以使用'爆炸('呢 - ',trim(' - 4-25-30',' - '))'。 –

试试这个

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

我想你使用explode()时夹杂了实际字符串分隔符。

正如我评论,如果你想从字符串中分离出所有数字,那么你需要使用函数PHP。您还需要使用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 
$odr="-4-25-30"; 
$str_array=explode("-",trim($odr,"-")); 
foreach ($str_array as $value){ 
printf("%d\n",$value); 
} 
?> 

应该让你在找什么

我试过所有的例子从上面的一些修复相结合

<?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"; 

Outpu T:

attempt 1: 
count: 3 
matches: array (
    0 => '4', 
    1 => '25', 
    2 => '30', 
) 
attempt 2: array (
    0 => '4', 
    1 => '25', 
    2 => '30', 
) 

为了实现与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 
)