0

私は文字列を持っており、preg_match_allその文字列でいくつかのタグを見つけるために使用しています:

$str = " 
Line 1: This is a string 
Line 2: [img]http://placehold.it/350x150[/img] Should not be [youtube]SDeWJqKx3Y0[/youtube] included."; 

preg_match_all("~\[img](.+?)\[/img]~i", $str, $img);  
preg_match_all("~\[youtube](.+?)\[/youtube]~i", $str, $youtube);

foreach ($img[1] as $key => $value) {
    echo '<img src="'.$value.'" "/>';
}

foreach ($youtube[1] as $key => $value) {
    echo '<iframe width="420" height="315" src="http://www.youtube.com/embed/'.$value.'" frameborder="0" allowfullscreen> </iframe>';
}

これは、正しい値でエコーされているものを正確に返します。

しかし、私が実際に望んでいるのは、これらの foreach ステートメントの値に置き換えられたタグ[img]とタグを含む文字列全体を返すことです。[youtube]

Line 1: This is a string 
    Line 2: <img src="http://placehold.it/350x150" "/> Should not be <iframe width="420" height="315" src="http://www.youtube.com/embed/SDeWJqKx3Y0" frameborder="0" allowfullscreen> </iframe> included.

私はサードパーティの代替手段を探しているのではなく、単純な php 関数を探しています。

preg_matchand some caseandステートメントを使用することを考えていますswitchが、まだ成功していません

アイデア?

4

1 に答える 1

1

preg_replaceを使用できます

こんな感じで。

$pattern = Array();
$pattern[0] = "~\[img](.+?)\[/img]~i";
$pattern[1] = "~\[youtube](.+?)\[/youtube]~i";

$replacement = Array();
$replacement[0] = '<img src="${1}" "/>';
$replacement[1] =  '<iframe width="420" height="315" src="http://www.youtube.com/embed/${1}" frameborder="0" allowfullscreen> </iframe>';

$stringToReturn = preg_replace($pattern, $replacement, $str);
于 2012-04-26T17:42:10.650 に答える