【问题标题】:how do i replace some tags and their content with custom text in php?如何用 php 中的自定义文本替换一些标签及其内容?
【发布时间】:2012-04-26 17:35:40
【问题描述】:

我有一个字符串,我使用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.

我不是在寻找第 3 方替代方案,只是简单的 php 函数。

我正在考虑使用preg_match 和一些caseswitch 语句,但我还没有成功

一个想法?

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • 看起来是这样做的。我之前尝试过同样的事情,但使用http://writecodeonline.com/php/ 时遇到了一堆错误。好像不能这样做
    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多