Özü bağlantı HTML dizesi niteliklerini

4 Cevap

$ Var dışarı HTML ayıklamak için en iyi yolu nedir?

$ var örneği

$var = "<a href="http://stackoverflow.com/">Stack Overflow</a>"

Ben istiyorum

$var2 = "http://stackoverflow.com/"

Örnek: preg_match ();

Başka ne var?

4 Cevap

Bunun yerine uzun karmaşık regex işçiliği, adımda bunu

$str = '<a href="http://stackoverflow.com/"> Stack Overflow</a>';
$str = preg_replace("/.*<a\s+href=\"/","",$str);
print preg_replace("/\">.*/","",$str);

patlayabilir kullanarak "non regex", tek yönlü

$str = '<a href="http://stackoverflow.com/"> Stack Overflow</a>';
$s = explode('href="',$str);
$t = explode('">',$s[1]);
print $t[0];

Eğer sahip geçerli bir HTML dizesi ise, o DOMDocument modülün loadHTML() fonksiyonu çalışacak ve çok kolayca yapısını gezinebilirsiniz. Bu, birlikte çalışmak için HTML bir sürü varsa bunu yapmak için iyi bir yoldur.

$doc = new DOMDocument();
$doc->loadHTML('<a href="http://stackoverflow.com/">Stack Overflow</a>');
$anchors = $doc->getElementsByTagName('a');
foreach($anchors as $node) {
    echo $node->textContent;
    if ($node->hasAttributes()) {
        foreach($node->attributes as $a) {
            echo ' | '.$a->name.': '.$a->value;
        }
    }
}

Aşağıdaki üretir:

Stack Overflow | href: http://stackoverflow.com/ 

strip_tags() removes HTML from the value of a variable. The second parameter is useful if you would like to make exceptions, and leave certain tags in, like the p aragraph etiketi.

$text = '<p>Paragraph.</p> <!-- boo --> <a href="#">Other text</a>';
echo strip_tags($text); // Paragraph. Other text
echo strip_tags($text, '<p><a>'); // <p>Paragraph.</p> <a href="#">Other text</a>

phpQuery

Uzakta Düzenli İfadeler uzak kalmak istiyorsanız, phpQuery değeri işlemek için kullanın ve sonra senin değerini almak için jQuery tarzı seçiciler ve yöntemleri kullanabilirsiniz:

// Bring in phpQuery
require("phpQuery-onefile.php");
// Load up our HTML
phpQuery::newDocumentHTML("<a href='http://sampsonresume.com/'>Homepage</a>");
// Print the HREF attribute of the first Anchor
print pq("a:first")->attr("href"); // http://sampsonresume.com/

Regex

Sen URL bulmak için aşağıdakileri kullanabilirsiniz:

$var = "<a href='http://sampsonresume.com/'>Homepage</a>";
preg_match("(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)",$var,$match);
print $match[0]; // http://sampsonresume.com/

Şu normal ifadeyi kullanabilirsiniz:

\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))