从字符串中获取特定内容

Get specific content from a string

我需要从给定的字符串中获取数字作为数组。

示例字符串:

$t = '1-P,2-T,3-P,4-R,5-C,6-T,';

预期输出:

array(
    [0] => 2,
    [1] => 6
)
array(
    [0] => 1,
    [1] => 3
)

我尝试了 var_export(explode("-T,",$t)); 但它没有按预期工作。 任何人都可以给我一个建议吗?

试试这个:

$t = '211111111131-P,2-T,3654554-P,4-R,5-C,6-T,';
$find = "-P";         // Search element
$found = [];          // Result array
$array = explode(",", $t);  // Breaking up into array 
foreach($array as $arr) {
    if (strpos($arr, $find)) {    // Checking if search element is found in $arr
       $found[] = explode('-',$arr)[0];  // Extracting the number prefix e.g 1 for 1-P
    }
}

输出:

Array
(
  [0] => 1
  [1] => 3
)

用作

$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$data = explode(",", $t);
print_r($data);
$row=array();
for ($i = 0; $i <= count($data); $i++) {
    if (!empty($data[$i])) {
        if (strpos($data[$i], '-T') !== false) {// pass find value here
            $final = explode("-", $data[$i]);
            $row[]=$final[0];
        }
    }
}
print_r($row);

输出

Array
(
    [0] => 2
    [1] => 6
)

DEMO

$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$temp = [];
// if the last comma is not typo the 3rd argument `-1` omit empty item
$array = explode(",", $t, -1);
foreach($array as $arr) {
   list($v, $k) = explode('-', $arr);
   $temp[$k][] = $v;  
}

print_r($temp['T']);

demo

下面匹配搜索词 -P.
之前的完整整数 让我们保持简洁:

$matches = array();
if (preg_match_all('/([0-9]+)\-P/', $t, $matches) >= 1) {
    var_dump($matches[1]);
}

搜索 '/([0-9]+)\-P/'/([0-9]+)\-C/'/([0-9]+)\-T/ 等等。


寻找不同搜索的更动态的方式terms/filters:

$filter = '-T';
$pattern = sprintf('/([0-9]+)%s/', preg_quote($filter));

参见 preg_match_all and preg_quote 函数。

这里已经有很多好的答案,但是 none 采取首先将数据放入更好的结构中的方法。

下面的代码将数据转换为关联数组,将字母映射到数字数组,这样您就可以根据需要的任意字母进行重复查找:

$t = '1-P,2-T,3-P,4-R,5-C,6-T,';

$a = array_filter(explode(',', $t));

$map = [];

foreach($a as $item) {
    $exploded = explode('-', $item);
    $number = $exploded[0];
    $letter = $exploded[1];
    if (!array_key_exists($letter, $map)) {
        $map[$letter] = [];
    }
    $map[$letter][] = $number;
}

print_r($map);
// Array
// (
//     [P] => Array
//         (
//             [0] => 1
//             [1] => 3
//         )
//
//     [T] => Array
//         (
//             [0] => 2
//             [1] => 6
//         )
//
//     [R] => Array
//         (
//             [0] => 4
//         )
//
//     [C] => Array
//         (
//             [0] => 5
//         )
//
// )

print_r($map['T']);
// Array
// (
//     [0] => 2
//     [1] => 6
// )
print_r($map['P']);
// Array
// (
//     [0] => 1
//     [1] => 3
// )