这是一个示例字符串:
$text = 'foo (20/50) bar () baz (11/30)';
我需要的输出是这样:
$items = array(
array(
"title" => "foo",
"number" => 20
),
array(
"title" => "bar",
"number" => 0
)
array(
"title" => "baz",
"number" => 11
)
);
到目前为止,我一直在使用
$matches_title = array();
$matches_number = array();
preg_match_all('!([^\s]+)!',$text,$matches_title);
preg_match_all('!(?<=\()(\d+)(?=\/)!',$text,$matches_number);
然后遍历匹配项以捕获值。显然,当括号之一为空时,这将不起作用,因为两个数组的长度都不同。
我该如何解决这个问题?
答案 0 :(得分:3)
您可以使用以下php代码:
$text = 'foo (20/50) bar () baz (11/30)';
preg_match_all('~([\w-]+)\h*\((\d*)(?=[/)])~', $text, $m);
$items = array();
foreach($m[1] as $i => $v) {
$n = $m[2][$i];
$items[] = array( "title" => $v, "number" => (empty($n) ? 0: $n) );
}
print_r($items);
输出:
Array
(
[0] => Array
(
[title] => foo
[number] => 20
)
[1] => Array
(
[title] => bar
[number] => 0
)
[2] => Array
(
[title] => baz
[number] => 11
)
)
答案 1 :(得分:1)
另一种选择是使用function getHubspotData(url) {
console.log("URL: " + url);
return fetch(url)
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
console.log(data);
return 2; // set resolved value of promise
}).then(function (x) {
console.log(x); // outputs 2
});
}
来匹配字符串的格式,以在上一个匹配项的末尾声明位置并使用命名的捕获组:
\G
例如:
\G(?<title>\S+)\h+\((?:(?<number>\d+)/\d+)?\)(?:\s|$)
结果:
$str = "foo (20/50) bar () baz (11/30)";
$pattern = '~\G(?<title>\S+)\h+\((?:(?<number>\d+)/\d+)?\)(?:\s|$)~';
preg_match_all($pattern, $str, $matches, PREG_SET_ORDER, 0);
$matches = array_reduce($matches, function($carry, $item) {
$carry[] = [
"title" => $item["title"],
"number" => array_key_exists("number", $item) ? $item["number"] : 0
];
return $carry;
});
print_r($matches);