我如何用PHP中的自定义文本替换一些标签及其内容?

时间:2012-04-26 17:35:41

标签: php preg-replace preg-match preg-match-all

我有一个字符串,我正在使用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>';
}

这将正确地返回正确值的回声。

但我真正想要的是返回整个字符串,其中[img][youtube]标记替换为来自这些foreach语句的值:

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_match和一些caseswitch语句,但我还没有成功

一个想法?

1 个答案:

答案 0 :(得分: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);