我有一个字符串,我希望从中获取值/字段。但是,这些值是#分隔的。
另外,从一个副本到下一个副本是逗号分隔的。
如下所示;
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";我需要循环这个字符串,获取一个记录的#分隔的值,另一个用逗号分隔的下一个记录。
字段的顺序是[TIME#FIRST_NAME#SECOND_NAME]。
我想不出有什么办法能完成这件事。
有没有人?
发布于 2018-01-23 11:40:04
使用分解将字符串解析为数组
<?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
}
?>发布于 2018-01-23 11:38:23
您可以使用explode和array_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://stackoverflow.com/questions/48400647
复制相似问题