在PHP中,使用preg_match
處理嵌套結構需要遞歸或使用其他方法。preg_match
主要用于處理簡單的正則表達式匹配,對于嵌套結構可能無法直接實現。在這種情況下,可以考慮以下兩種方法:
function preg_match_nested($pattern, $string, &$matches = []) {
if (!isset($matches)) {
$matches = [];
}
preg_match($pattern, $string, $temp_matches);
if (!empty($temp_matches)) {
foreach ($temp_matches as $key => $match) {
if (is_array($match)) {
preg_match_nested($pattern, $match[0], $matches);
} else {
$matches[] = $match;
}
}
}
return count($matches) > 0;
}
$pattern = '/\(([^()]+)\)/';
$string = '這是一個(例子(嵌套))結構';
$matches = [];
if (preg_match_nested($pattern, $string, $matches)) {
print_r($matches);
} else {
echo '沒有匹配到嵌套結構';
}
Symfony DomCrawler
,可以更輕松地處理嵌套結構:require_once 'vendor/autoload.php';
use Symfony\Component\DomCrawler\Crawler;
$html = '這是一個(例子(嵌套))結構';
$crawler = new Crawler($html);
$pattern = '/\(([^()]+)\)/';
$matches = [];
foreach ($crawler->filter('div') as $div) {
preg_match_all($pattern, $div->textContent, $temp_matches);
if (!empty($temp_matches[1])) {
foreach ($temp_matches[1] as $match) {
$matches[] = $match;
}
}
}
print_r($matches);
這兩種方法都可以處理嵌套結構,但遞歸函數更靈活,可以適應不同深度的嵌套。而Symfony DomCrawler
庫則更適合處理HTML文檔。根據實際需求選擇合適的方法。