2017-03-12 14 views
0

内容:のhrefを除くすべてのhref 'ラッパー' は、特定の値が含まれて削除:PHP

<a href="http://www.lipsum.com/">Lorem Ipsum</a> is simply dummy text 
of the printing and typesetting industry. 
<a href="http://www.google.com/1111/2222/3333">Lorem Ipsum</a> has been the industrys 
standard dummy text ever since the 1500s, when an unknown printer 
took a <a href="http://gallery.com">galley</a> of type and scrambled 
it to make a type specimen <a href="http://www.google.com/1111/3333/4444">book</a>. 

コンテンツは、私はこの結果をしたい3 "のhref" リンク

http://www.lipsum.com/ 
http://www.google.com/1111/2222/3333 
http://www.google.com/1111/3333/4444 
http://gallery.com/ 

が含まれています。選択されたhref値はhref="http://google.com/1111/3333****のみ

Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type 
specimen <a href="http://www.google.com/1111/3333/4444">book</a>. 

誰でもこの方法を知っていますか?あなたはその質問を理解することを望みます。前もって感謝します。

答えて

1

正規表現での内容の解析と変換はお勧めできません。
しかし、あなたは、次のpreg_replaceソリューション使用することができます(たとえば、"Lorem Ipsum")あなたの小断片のために、自身を削除しながら、あなたはリンクテキストを保持する必要があることを考慮:

$html = '<a href="http://www.lipsum.com/">Lorem Ipsum</a> is simply dummy text 
of the printing and typesetting industry. 
<a href="http://www.google.com/1111/2222/3333">Lorem Ipsum</a> has been the industrys 
standard dummy text ever since the 1500s, when an unknown printer 
took a <a href="http://gallery.com">galley</a> of type and scrambled 
it to make a type specimen <a href="http://www.google.com/1111/3333/4444">book</a>.'; 

$re = '/<a href="http:\/\/(?!www\.google\.com\/1111\/3+\/[^>]+).*?>([^<>]+)<\/a>/m'; 
$result = preg_replace($re, "$1", $html); 

echo $result; 

出力:

Lorem Ipsum is simply dummy text 
of the printing and typesetting industry. 
Lorem Ipsum has been the industrys 
standard dummy text ever since the 1500s, when an unknown printer 
took a galley of type and scrambled 
it to make a type specimen <a href="http://www.google.com/1111/3333/4444">book</a>. 

(?!www\.google\.com\/1111\/3+\/[^>]+) - lookahead否定アサーションは、リンクに一致します。これらの属性値はneに適合しませんeded要件href="http://www.google.com/1111/3333****

----------

、より正確な方法は、のDOMDocument/を使用することになりDOMXPathを使うことの最大クラス:

$dom = new \DOMDocument(); 
$dom->loadHTML($html); 
$xpath = new \DOMXPath($dom); 

$nodes = $xpath->query("//a[not(contains(@href, 'http://www.google.com/1111/3333'))]"); 
foreach ($nodes as $n) { 
    $n->parentNode->replaceChild($dom->createTextNode($n->nodeValue), $n); 
} 

echo $dom->saveHTML($dom->documentElement); 

出力:

<html><body>Lorem Ipsum is simply dummy text 
of the printing and typesetting industry. 
Lorem Ipsum has been the industrys 
standard dummy text ever since the 1500s, when an unknown printer 
took a galley of type and scrambled 
it to make a type specimen <a href="http://www.google.com/1111/3333/4444">book</a>.</body></html> 
関連する問題