Ben HTML üzerinde RegEx kullanarak, cletus katılıyorum çünkü bir dil olarak nasıl gevşek HTML kötü uygulamadır (ve ben PHP ... çok gevşek olma konusunda inilti). Eğer belge standartlarına uyumlu / katı olduğunu bilmiyorsanız, bazen yapmak için sadece imkansız olduğunu bir etiketi değişken olabilir sadece çok yolu vardır. İşten beni oyalar bir meydan okuma gibi Ancak, çünkü burada RegEx'in bunu yapabilir nasıl!
Ben bölüme bu kadar bölünmüş olacak, gördüğünüz her bir dize ve, derseniz hiçbir nokta "Meh ... It yapacağım ..."! Öncelikle bir çapa etiketi için ana RegEx var:
'#<a></a>#'
Then we add in the text that could be between the tags.
We want to group this is parenthesis, so we can extract the string, and the question mark makes the asterix wildcard "un-greedy", meaning that the first </a>
that it comes accross will be the one it uses to end the RegEx.
'#<a>(.*?)</a>#'
Sonraki biz href = "" için RegEx'in eklemek. Biz, düz metin olarak biten tırnak işareti, sonra bir tırnak işareti içermiyorsa sonra herhangi uzunlukta bir dize href="
maç.
'#<a href\="([^"]*)">(.*?)</a>#'
Now we just need to say that the tag is allowed other attributes. According to the specification, an attribute can contain the following characters: [a-zA-Z_\:][a-zA-Z0-9_\:\.-]*
.
Allow an attribute multiple times, and with a value, we get: ( [a-zA-Z_\:][a-zA-Z0-9_\:\.-]*\="[^"]*")*
.
Oluşan RegEx (PCRE) aşağıdaki gibidir:
'#<a( [a-zA-Z_\:][a-zA-Z0-9_\:\.-]*\="[^"]*")* href\="([^"]*)"( [a-zA-Z_\:][a-zA-Z0-9_\:\.-]*\="[^"]*")*>(.*?)</a>#'
Şimdi, PHP, dize tüm tekrarlarını kapmak için preg_match_all()
işlevini kullanın.
$regex = '#<a( [a-zA-Z_\:][a-zA-Z0-9_\:\.-]*\="[^"]*")* href\="([^"]*)"( [a-zA-Z_\:][a-zA-Z0-9_\:\.-]*\="[^"]*")*>(.*?)</a>#';
preg_match_all($regex, $str_containing_anchors, $result);
foreach($result as $link)
{
$href = $link[2];
$text = $link[4];
}