我制作了这段代码:
$matches = array();
preg_match_all('/"Type":".+?",/', $text, $matches);
foreach($matches[0] as $match) {
if (isset($_GET['dvd']) && !empty($_GET['dvd'])) {
$dvd = $_GET['dvd'];
if (stripos($match, 'DVD') !== false) {
$match = '';
}
}
echo $match;
}
在这段代码中,我在$ text中搜索单词“type”,它会在整个行中存储数组前面的单词。然后我遍历每一个,看看DVD是否存在。如果是,则删除它并显示一个空行。
现在我也想搜索假设的制造商并将其显示在返回的每种类型下面。
所以它应该返回假设结果:
Type: HDD
Manufacturer: WD
Type: Flash Drive
Manufacturer: Transcend
Type: CD
Manufacturer: Sony
所以我尝试了另外一个preg_match_all表达式:
$anotherMatch = array();
preg_match_all('/"Manufacturer":".+?",/', $text, $anotherMatch);
我尝试将此与前一个foreach表达式结合使用&&运营商,但它没有工作。此外,我尝试了不同的foreach表达式,然后一个用于回声结束。但这也行不通。
你能告诉我如何达到预期的效果吗?感谢...
答案 0 :(得分:0)
给出这样的源输入:
"Type":"HDD",
"Manufacturer":"WD",
"Other":"Nonsense",
"Type":"Flash Drive",
"Manufacturer":"Transcend",
"Other":"More nonsense",
"Type":"CD",
"Manufacturer":"Sony",
"Other":"Yet even more nonsense",
期待这样的输出:
Type: HDD
Manufacturer: WD
Type: Flash Drive
Manufacturer: Transcend
Type: CD
Manufacturer: Sony
您可以使用此正则表达式:
/"(Type|Manufacturer)":"([^"]+?)",/
然后像这样循环:
preg_match_all('/"(Type|Manufacturer)":"([^"]+?)",/', $text, $matches);
foreach($matches[0] as $match => $line)
{
if (!empty($_GET['dvd']) && stripos($matches[2], 'DVD') !== false)
{
continue;
}
echo $matches[1][$match] . ': ' . $matches[2][$match] . "\n";
}
虽然,我认为这不会完全符合您的要求。