2011-01-11 16 views
0

ファイルを検索して単語のリストを一致する置換語句に置き換える小さなスクリプトがあります。アンカータグ、imgタグ、または実際に指定した1つのタグに表示されている場合、preg_replaceがこれらの単語を置き換えるのを防ぐ方法も見つけました。私は、複数のタグを指定できるようにするには、ORステートメントを作成したいと思います。明確にするために、私はpreg_replaceがアンカータグに表示されるだけでなく、anchor、link、embed、object、img、またはspanタグに現れる単語を置き換えるのを防ぎたいと思います。私は '|' OR演算子はコード内のさまざまな場所で成功しません。基本的には内部の「赤」のではなく、検索するために言う最初の検索用語を見てPHPコーディング複数のタグからPreg_replace関数を制限する

<?php 
$data = 'somefile.html'; 
$data = file_get_contents($data); 
$search = array ("/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(white)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(blue)\b/is"); 
$replace = array ('Apple','Potato','Boysenberry'); 
echo preg_replace($search, $replace, $data);?> 
print $data; 
?> 

:私は何とか< \ /リンクを追加する方法を把握しようとしています

"/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is" 

>、 < \/embed>、< \/object>、< \/img>のいずれかのタグでpreg_replaceが 'red'に置き換えられないようにします。

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self- contains-tags/1732454#1732454 – dqhendricks

+0

PHP DOMクラスを使用して、代わりにHTMLドキュメントをトラバースします。 – dqhendricks

答えて

0

このような何か?:

<?php 
    $file = 'somefile.html'; 
    $data = file_get_contents($file); 
    print "Before:\n$data\n"; 
    $from_to = array("red"=>"Apple", 
        "white"=>"Potato", 
        "blue"=>"Boysenberry"); 
    $tags_to_avoid = array("a", "span", "object", "img", "embed"); 
    $patterns = array(); 
    $replacements = array(); 

    foreach ($from_to as $from=>$to) { 
    $patterns[] = "/(?!(?:[^<]*>|[^>]+<\/(".implode("|",$tags_to_avoid).")>))\b".preg_quote($f 
rom)."\b/is"; 
    $replacements[] = $to; 
    } 

    $data = preg_replace($patterns, $replacements, $data); 

    print "After:\n$data\n"; 
    ?> 

結果:

Before: 
<a href="red.html">red</a> 
<span class="blue">red</span> 
blue<div class="blue">white</div> 
<div class="blue">red</div> 

After: 
<a href="red.html">red</a> 
<span class="blue">red</span> 
Boysenberry<div class="blue">Potato</div> 
<div class="blue">Apple</div> 
関連する問題