Sizin iş için bir HTML string, regex are generally not the right/best tool bazı veri ayıklamak için çalışıyoruz göz önüne alındığında.
Bunun yerine, neden hiçbir kullanımı DOM parser gibi DOMDocument PHP ile sağlanan sınıf , ve DOMDocument::loadHTML a> yöntemi ?
Ardından, DOM yöntemlerini kullanarak HTML belgesinde gezinmek olabilir - özellikle HTML oldukça regular daha düşünüyor, regex kullanarak çok daha kolay olduğu.
Here, for example, you could use something like this :
$html = <<<HTML
<li class="zk_list_c2 f_l"><a title="abc" target="_blank" href="link">
abc
</a> </li>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$as = $dom->getElementsByTagName('a');
foreach ($as as $a) {
var_dump($a->getAttribute('href'));
var_dump(trim($a->nodeValue));
}
Ve aşağıdaki çıktıyı almak istiyorum:
string(4) "link"
string(3) "abc"
The code is not quite hard, I'd say, but, in a few words, here what it's doing :
Sadece bir not: href özellik varsa onun değerini kullanmayı denemeden önce, DOMElement::hasAttribute a> ile kontrol etmek isteyebilirsiniz ...
EDIT after the comments : here's a quick example using DOMXpath to get to the links ; I supposed you want the link that's inside the <li> tag with class="zk_list_c2 f_l" :
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$as = $xpath->query('//li[@class="zk_list_c2 f_l"]/a');
foreach ($as as $a) {
var_dump($a->getAttribute('href'));
var_dump(trim($a->nodeValue));
}
Ve yine, olsun:
string(4) "link"
string(3) "abc"
As you can see, the only thing that changes is the way you're using to get to the right <a> tag : instead of DOMDocument::getElementsByTagName, it's just a matter of :