Çapa etiketleri PHP RegEx (veya Alt Yöntemi)

5 Cevap php

Tamam ben bir soap isteği ayrıştırmak zorunda ve isteğinde bazı değerlerin (ya da iç) bir Anchor etiketi geçirilir. Etiketi şerit ve sadece değer döndürmek için bir RegEx'in (veya alt yöntemi) arıyorum.

// But item needs to be a RegEx of some sort, it's a field right now
if($sObject->list == 'item') {
   // Split on > this should be the end of the right side of the anchor tag
   $pieces = explode(">", $sObject->fields->$field);

   // Split on < this should be the closing anchor tag
   $piece = explode("<", $pieces[1]);

   $fields_string .= $piece[0] . "\n";
}

öğe bir alan adı ama ben bu Anchor etiketinin yerine belirli bir alanda kontrol etmek için bir RegEx yapmak istiyorum.

5 Cevap

PHP a strip_tags() işlevi vardır.

Alternatif Kullanmak filter_var() with FILTER_SANITIZE_STRING. Olabilir

Ne yaparsan yap, düzenli ifadeler ile HTML / XML ayrıştırmak değil. Gerçekten hata eğilimli ve lapa lapa bulunuyor. PHP, standart olarak en az 3 farklı ayrıştırıcıları (akla SimpleXML , DOMDocument and XMLReader yay) sahiptir.

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];
 }

İstediğiniz düğümleri almak için simplexml ve XPath'i kullanabilirsiniz

Eğer istek çeşit yoksa <-> sınıf haritalama DOM extension ile bilgi elde edebilirsiniz. Özelliği textConent bağlamsal düğüm ve onun soyundan tüm metnini içerir.

$sr = '<?xml version="1.0"?>
<SOAP:Envelope xmlns:SOAP="urn:schemas-xmlsoap-org:soap.v1">
  <SOAP:Body>
    <foo:bar xmlns:foo="urn:yaddayadda">
       <fragment>
         <a href="....">Mary</a> had a
         little <a href="....">lamb</a>
       </fragment>
    </foo:bar>
  </SOAP:Body>
</SOAP:Envelope>';

$doc = new DOMDocument;
$doc->loadxml($sr);

$xpath = new DOMXPath($doc);
$ns = $xpath->query('//fragment');
if ( 0 < $ns->length ) {
  echo $ns->item(0)->nodeValue;
}

baskılar

Mary had a
little lamb

Yalnızca belirli etiketi özelliklerini şerit veya ayıklamak istiyorsanız, DOMDocument denemelisiniz.

Böyle bir şey:


$TagWhiteList = array(
    // Example of WhiteList
    'b', 'i', 'u', 'strong', 'em', 'a', 'img'
);

function getTextFromNode($Node, $Text = "") {
    // No tag, so it is a text
    if ($Node->tagName == null)
        return $Text.$Node->textContent;

    // You may select a tag here
    // Like:
    // if (in_array($TextName, $TagWhiteList)) 
    //     DoSomthingWithIt($Text,$Node);

    // Recursive to child
    $Node = $Node->firstChild;
    if ($Node != null)
        $Text = getTextFromNode($Node, $Text);

    // Recursive to sibling
    while($Node->nextSibling != null) {
        $Text = getTextFromNode($Node->nextSibling, $Text);
        $Node = $Node->nextSibling;
    }
    return $Text;
}

function getTextFromDocument($DOMDoc) {
    return getTextFromNode($DOMDoc->documentElement);
}

Kullanmak için:

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");

$Text = getTextFromDocument($Doc); echo "Text from HTML: ".$Text."\n";

Yukarıdaki fonksiyon etiketleri şerit nasıl olduğunu. Ama elemanını işlemek için bunu biraz değiştirebilirsiniz. Etiketi archor 'a' Örneğin, sen hedefine ayıklamak yerine içine metin görüntüler.

Umarım bu yardımcı olur.