我有一个字符串,我使用 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
和一些case
和switch
语句,但我还没有成功
一个想法?
您可以使用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);