주석에서 언급했듯이 정규 표현식으로 HTML에서 항목을 추출하려고 시도하는 것은 좋지 않습니다. 더 방탄 방법으로 전환하고 싶다면 여기 DOMDocument API를 사용하여 쉽게 정보를 추출하는 방법에 대한 간단한 예가 있습니다.
<?php
function get_vboxview($html) {
$output = array();
// Create a new DOM object
$doc = new DOMDocument;
// load a string in as html
$doc->loadHTML($html);
// create a new Xpath object to query the document with
$xpath = new DOMXPath($doc);
// an xpath query that looks for a vboxview node anywhere in the DOM
// with an attribute named leftinset set to 10, an attribute named rightinset
// set to 0 and an attribute named stretchiness set to 1
$query = '//vboxview[@leftinset=10 and @rightinset=0 and @stretchiness=1]';
// query the document
$matches = $xpath->query($query);
// loop through each matching node
// and the textContent to the output
foreach ($matches as $m) {
$output[] = $m->textContent;
}
return $output;
}
?>
더 나은 아직 단 하나의 vboxview
귀하의 의견에가있을 보장되는 경우 vboxview
에 id
속성을 추가하고 짧은 더 일반화에 아래의 코드를 줄일 수 (또한 가정 당신은 HTML의 제어 할 수 있습니다) 기능.
<?php
function get_node_text($html, $id) {
// Create a new DOM object
$doc = new DOMDocument;
// load a string in as html
$doc->loadHTML($html);
// return the textContent of the node with the id $id
return $doc->getElementById($id)->textContent;
}
?>
XML 구문 분석기를 사용하십시오. Regexex는 XML 또는 HTML 구문 분석 용으로 설계되지 않았습니다. – Cfreak
괜찮 았지만 그 다음 preg_match_all은 무엇을 위해 사용 되었습니까 ?? php.net에서 html을 파싱하는 예제를 실제로 보여주기 때문입니다. –
@AhouraGhotbi - 예, 좋지 않은 예이며 변경해야합니다. 정규식은 패턴이있는 데이터를 구문 분석하기위한 것입니다. 정의에 의한 XML과 HTML은 구조화되어 있지 않습니다. 정규식을 사용하여 구문 분석 할 수 있지만 파일을 특정 방식으로 구성 할 필요가 없으므로 좋은 생각이 아닙니다. 다른 말로하면 누군가가 당신에게 사양에 맞는 XML 파일을 제공하더라도 프로그램이 중단 될 위험이 높습니다. – Cfreak