如何使用PHP字符串中的SPACE获取数字范围?

时间:2017-07-24 07:35:51

标签: php laravel preg-match

我有这样的表值。

男孩 - 年龄0 - 1

女性

男孩 - 年龄1 - 2

男孩 - 1岁

男孩 - 2岁

女孩 - 3岁至4岁

男孩 - 1岁

男孩 - 2岁

原始阵列:

    [ 0 => "Boys - Age 0 - 1" 1 => "Women" 2 => "Boys - Age 0 - 1" 
3 => "Boys - Age 1" 4 => "Boys - Age 2" 5 => "Boys - Age 3" 
6 => "Boys - Age 4" 7 => "Boys - Age 5" 8 => "Boys - Age 6" 
9 => "Boys - Age 7" 10 => "Boys - Age 8" 11 => "Boys - Age 9" ]

现在我想从我尝试爆炸的这些值中获得唯一的大小,但它给出了我在第3个索引中的大小,有时候第2个索引是不可接受的。

OUTPUT我需要这样的foreach循环。 0 - 1

妇女

1 - 2

1

2

3 - 4

1

2

示例数据enter image description here

4 个答案:

答案 0 :(得分:2)

试试这个

foreach ($data as $val) {
    $splitVal = explode('-', $val);
  if (isset($splitVal[1])) {
    $finalResult[] = filter_var($splitVal[1], FILTER_SANITIZE_NUMBER_INT).(isset($splitVal[2])?'-'.$splitVal[2]:'');
    }    
}

答案 1 :(得分:0)

这样的东西?

foreach ($arr as $val) {
    $matches = array();
    if (preg_match('/\d(\s-\s\d)?/', $val, $matches)) {
        echo $matches[0].'<br>'; // Or whatever you want to make with that result
    }
}

此代码检索由数字组成的字符串部分,最后跟一个连字符和另一个数字,并打印出来。当然,该行可以替换为将其放入数组中。

答案 2 :(得分:0)

尝试此操作以获取值:

$array = array( 0 => "Boys - Age 0 - 1", 1 => "Women", 2 => "Boys - Age 0 - 1", 3 => "Boys - Age 1", 4 => "Boys - Age 2", 5 => "Boys - Age 3", 6 => "Boys - Age 4" ,7 => "Boys - Age 5" ,8 => "Boys - Age 6", 9 => "Boys - Age 7", 10 => "Boys - Age 8", 11 => "Boys - Age 9" ) ;

foreach( $array as $key => $value ){
$value_number=explode('Boys - Age',$value);
if (isset($value_number[1]))
    echo $value_number[1]."\n";
}
$value_number=explode('Girls - Age',$value);
if (isset($value_number[1]))
    echo $value_number[1]."\n";
}
$value_number=explode('Kids - Age',$value);
if (isset($value_number[1]))
    echo $value_number[1]."\n";
}

答案 3 :(得分:0)

使用以下代码:

<强>代码:

<?php

$arr = array( 0 => "Boys - Age 0 - 1", 1 => "Women", 2 => "Boys - Age 0 - 1", 3 => "Boys - Age 1", 4 => "Boys - Age 2", 5 => "Boys - Age 3", 6 => "Boys - Age 4", 7 => "Boys - Age 5", 8 => "Boys - Age 6", 9 => "Boys - Age 7", 10 => "Boys - Age 8", 11 => "Boys - Age 9" );

foreach($arr as $row) {
    $array = explode('-', $row, 2);
    if($array[1] != '')
        $finalArr[] = trim(str_replace('Age ','',$array[1]));
}

print_r($finalArr);

<强>输出

Array
(
    [0] => 0 - 1
    [1] => 0 - 1
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 4
    [6] => 5
    [7] => 6
    [8] => 7
    [9] => 8
    [10] => 9
)

演示:Click Here