如何使用 PHP 中的 preg_match 从字符串创建数组
How to create Array from a String with preg_match in PHP
我有如下字符串
Ref ID =={1234} [201] (text message)
我想创建一个像下面这样的数组
array(
0 => 1234,
1 => 201,
2 => "text message"
)
现在我正在使用 Exploding the string 方法,但它需要 8 行代码,多次爆炸,如下所示。
$data = array();
$str = 'Ref ID =={1234} [201] (text message)';
$bsArr1 = explode('}', $str);
$refIdArr = explode('{', $bsArr1);
$data[0] = $refIdArr[1];
$bsArr2 = explode(']', $bsArr[1]);
$codeArr = explode('[', $bsArr2[0]);
....
....
....
有没有办法用 preg_match 实现这个?
简单的preg_match:
preg_match('/{(\d+)}.*\[(\d+)].*\(([a-zA-Z ]+)\)/', 'Ref ID =={1234} [201] (text message)', $matches);
$arr[] = $matches[1];
$arr[] = $matches[2];
$arr[] = $matches[3];
echo '<pre>';
var_dump($arr);
die();
这将找到 [{(
之一并捕获所有跟随 }])
的懒惰
$str = "Ref ID =={1234} [201] (text message)";
preg_match_all("/[{|\[|\(](.*?)[\]|\)\}]/", $str, $matches);
var_dump($matches);
输出:
array(2) {
[0]=>
array(3) {
[0]=>
string(6) "{1234}"
[1]=>
string(5) "[201]"
[2]=>
string(14) "(text message)"
}
[1]=>
array(3) {
[0]=>
string(4) "1234"
[1]=>
string(3) "201"
[2]=>
string(12) "text message"
}
}
我有如下字符串
Ref ID =={1234} [201] (text message)
我想创建一个像下面这样的数组
array(
0 => 1234,
1 => 201,
2 => "text message"
)
现在我正在使用 Exploding the string 方法,但它需要 8 行代码,多次爆炸,如下所示。
$data = array();
$str = 'Ref ID =={1234} [201] (text message)';
$bsArr1 = explode('}', $str);
$refIdArr = explode('{', $bsArr1);
$data[0] = $refIdArr[1];
$bsArr2 = explode(']', $bsArr[1]);
$codeArr = explode('[', $bsArr2[0]);
....
....
....
有没有办法用 preg_match 实现这个?
简单的preg_match:
preg_match('/{(\d+)}.*\[(\d+)].*\(([a-zA-Z ]+)\)/', 'Ref ID =={1234} [201] (text message)', $matches);
$arr[] = $matches[1];
$arr[] = $matches[2];
$arr[] = $matches[3];
echo '<pre>';
var_dump($arr);
die();
这将找到 [{(
之一并捕获所有跟随 }])
$str = "Ref ID =={1234} [201] (text message)";
preg_match_all("/[{|\[|\(](.*?)[\]|\)\}]/", $str, $matches);
var_dump($matches);
输出:
array(2) {
[0]=>
array(3) {
[0]=>
string(6) "{1234}"
[1]=>
string(5) "[201]"
[2]=>
string(14) "(text message)"
}
[1]=>
array(3) {
[0]=>
string(4) "1234"
[1]=>
string(3) "201"
[2]=>
string(12) "text message"
}
}