从#

时间:2018-01-23 11:29:36

标签: php string

我有一个字符串,我想从中获取值/字段。但是,值#是分开的。

此外,从一个副本到下一个副本,它以逗号分隔。

如下图所示;

$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";

我需要循环遍历此字符串,将#分隔的值分隔为一条记录,以逗号分隔的下一条记录。

字段的顺序为[TIME#FIRST_NAME#SECOND_NAME]

我无法想办法让这件事完成。

任何?

2 个答案:

答案 0 :(得分:2)

您可以使用explodearray_map

来使用以下解决方案
$transaction = "
    [2018-01-10 12:50:07.822#SAMUEL#TITUS],
    [20120605152613#KEN#NAUGH],
    [20120705152645#JOHHY#BRAVO]";

//normalize the string and remove the unnecessary chars.
$transaction = str_replace(['[', ']', "\n"], '', $transaction);

//get all the rows as array.
$rows = explode(',', $transaction);

//create the columns in rows.
$row_arr = array_map(function ($row) {
    return explode('#', $row);
}, $rows);

//info of the first row.
echo $row_arr[0][0]; // time
echo $row_arr[0][1]; // firstname
echo $row_arr[0][2]; // lastname

//run through the rows to output.
foreach ($row_arr as $row_item) {
    echo 'Time: '.$row_item[0].', Firstname: '.$row_item[1].', Lastname: '.$row_item[2]."<br>";
}
  

演示: https://ideone.com/3uYcSw

答案 1 :(得分:2)

使用explode将字符串解析为数组

<?php
$transaction = "[2018-01-10 12:50:07.822#SAMUEL#TITUS],[20120605152613#KEN#NAUGH],[20120705152645#JOHHY#BRAVO]";
$parsed = explode(",", $transaction);

foreach($parsed as $val){

    $val = explode("#", $val);
    $first_name = $val[1];
    $last_name = str_replace("]", '', $val[2]);

    echo $first_name." ".$last_name."<br>"; // get firstname & lastname 

}

?>