你好,我的正则表达式有问题。
例如,我有这个文本
$textMessage = "|nif|<00/00/03364301P>|lat|<not set>|long|<not set>|deviceId|<1F26DE6896ADC816-001346E604E7>|messageId|<70154>";
我想要一个像这样的阵列
$data = array(
array("nif" => "00/00/03364301P"),
array("lat" => "not set") // etc
)
使用字符串中的所有数据,我尝试了这个函数。
function getArrayDataSMS($textMessage){
$regexType = '/'|([a-zA-Z]+)'||<['d]+>/';
$rowValueData = preg_match_all($regexType, $textMessage, $matches, PREG_SET_ORDER);
foreach ($matches as $key => $match) {
$arrayData[trim($match[1])] = trim($match[2]);
}
return $arrayData;
}
但是响应不是正确的
array(2) {
[0]=>
string(5) "|nif|"
[1]=>
string(3) "nif"
}
array(3) {
[0]=>
string(6) "<4545>"
[1]=>
string(0) ""
[2]=>
string(4) "4545"
}
你知道吗。
非Regex
$textMessage="|nif|<00/00/03364301P>|lat||long||deviceId|<1F26DE6896ADC816-001346E604E7>|messageId|<70154>";
使用上面的字符串,您可以使用此脚本将其处理为所需的数组。
$array = explode("|",$textMessage);
var_dump($array);
$data = array();
//Start with 1 since $array[0] is '';
//Assumed first and last characters <> are present and need to be removed
//Feel free to modify as needed
for($i = 1; $i < count($array); $i+=2) {
$data[] = array($array[$i] => substr($array[$i+1], 1, -1));
}
echo "<pre>";
print_r($data);
输出
Array (
[0] => Array (
[nif] => 00/00/03364301P
)
[1] => Array (
[lat] => not set
)
[2] => Array (
[long] => not set
)
[3] => Array (
[deviceId] => 1F26DE6896ADC816-001346E604E7
)
[4] => Array (
[messageId] => 70154
)
)
试试这个:
$text = "|nif|<00/00/03364301P>|lat|<not set>|long|<not set>|deviceId|<1F26DE6896ADC816-001346E604E7>|messageId|<70154>";
preg_match_all("/'|('w+?)'|'<(.+?)>/",$text,$a);
$result = array_combine($a[1],$a[2]);