2012-02-23 25 views
0

可能性の重複を置き換える:
PHP - remove <img> tag from string文字列から画像タグを削除し、文字列で

は、私は、文字列から画像タグを削除すると同時に、何かでそれを交換する必要があります。ここで私が持っているものです。

$body = '<p>Lorem ipsum dolor sit amet:</p> 
<p><img class="news" id="" src="images/news_48.png" alt="" /></p> 
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p> 
<p><img class="gallery" id="26" src="images/gallery_48.png" alt="" /></p> 
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>'; 

それは=「ギャラリー」クラスの場合、画像は、クラス=「ニュース」と別のものを持っている場合、私は一つのことを行う必要があります。 $body今では

<?php 
    if(news){ 
     replace the image tag where class=news with %%news%% 
    } 
    if(gallery){ 
     replace the image tag where class=gallery with %%gallery%% 
     assign the value 26 to some variable 
    } 
?> 

含まれます:私は次のようにいくつかの擬似コードを考えている

$body = '<p>Lorem ipsum dolor sit amet:</p> 
<p>%%news%%</p> 
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p> 
<p>%%gallery%%</p> 
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>'; 

を私は/置換するpreg_matchを使用する必要が推測するが、私は正規表現が得意ではないんです。どんな助けもありがとうございます。

+0

htmlで正規表現を使用するたびに、子猫が踏みつぶされます。 –

+0

@MarkB http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tagsこれは(そうでない場合)このウェブサイトで最も一般的な回答の1つです。 – annonymously

+0

またはhttp://stackoverflow.com/questions/1107194/php-remove-img-tag-from-string – krlmlr

答えて

0

あなたはこのようにそれを行うことができます。

<?php 
$body = '<p>Lorem ipsum dolor sit amet:</p> 
<p><img class="news" id="" src="images/news_48.png" alt="" /></p> 
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p> 
<p><img class="gallery" id="26" src="images/gallery_48.png" alt="" /></p> 
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>'; 

if (preg_match('{.*<img class="gallery".*}', $body)) { 
    $some_variable = 26; 
} 

print preg_replace('{<img class="(news|gallery)".*/>}', '%%\\1%%', $body); 

?> 
0

おかげで、私はこれで終わりました。それは一種の:)

<?php 
    $str = preg_replace('/<img class="news"[^>]+\>/i', "%%news%%", $str); 
    preg_match('/<img class="gallery" id="(.*?)"[^>]+\>/i', $str, $id); 
    $id = $id[1]; 
    $str = preg_replace('/<img class="gallery"[^>]+\>/i', "%%gallery%%", $str); 
    echo $str; 
?> 

に動作します。しかし、私は私は2枚の以上のギャラリー画像を持っていると、あまりにも自分のIDを取得したい場合は、何を考えました。 %% gallery %%は、何らかの方法で各%% gallery %%のそれぞれのIDにリンクする必要があります。

関連する問題