【问题标题】:find and replace all occurrences of string [php shortcodes]查找并替换所有出现的字符串 [php 简码]
【发布时间】:2016-02-03 23:33:47
【问题描述】:

我正在使用此代码将 CMS 中的简码替换为包含图像的链接,但它仅替换第一个简码

$string = $row['Content'];
  if(stristr($string,'[gal=')){
    $startTag = "[gal=";
    $endTag = "]";
    $pos1 = strpos($string, $startTag) + strlen($startTag);
    $pos2 = strpos($string, $endTag);
    $gal = substr($string, $pos1, $pos2-$pos1);
    $q=$db->prepare("select * from images where Gal_ID = :gal");
    $q->execute(["gal"=>$gal]);
    $imgs='';
    while($r=$q->fetch(PDO::FETCH_ASSOC)){
        $images[] = $r['Image'];
    }
    foreach($images as $val){
        $imgs .= "<a href='gallery/large/$val' class='fancybox-thumbs' rel='gallery'><img src='gallery/thumb/$val'></a>";
    }
    $result = substr_replace($string, $imgs, $pos1, $pos2-$pos1);
    $result = str_replace($startTag,'',$result);
    $result = str_replace($endTag,'',$result);
    echo $result;
 }
 else{
    echo $string;
 }

字符串包含一些段落和 2 个简码

[gal=36] and [gal=37]

结果是仅用链接和图像替换第一个短代码,但第二个短代码显示如下:“37”只是数字。那么如何遍历所有简码以将它们替换为链接,而不仅仅是第一个简码

【问题讨论】:

  • 这应该通过正则表达式替换来完成,以便替换所有实例,而不仅仅是第一个。稍后我会回来,如果没有人帮忙,我会尝试为你写这篇文章。
  • 我建议使用正则表达式来匹配简码。就个人而言,我会 preg_match 所有现有代码,将它们集中到一个查询中,运行它并将其格式化为一个数组。然后 preg_replace_callback 用查找结果数组替换短代码。您最终会调用两次正则表达式模式,但只有一个查询会是最慢的部分。
  • $q=$db-&gt;prepare("select * from images where Gal_ID = '$gal'"); 警告:注入内在。这不是因为您使用的是PDO::prepare,您可以以某种方式安全地将值串入查询中。你应该使用SELECT * FROM images WHERE Gal_ID = :id$q-&gt;execute([':id' =&gt; $gal]);
  • Elias Van Ootegem:我只是为了解释而插入了没有绑定的变量,但我总是使用 bindParam 来保护查询

标签: php regex loops str-replace strstr


【解决方案1】:

这是我上面描述的完整示例。

//get matches
if(preg_match_all('/\[gal=(\d+)\]/i', $string, $matches) > 0){
    //query for all images. You could/should bind this, but since the expression
    //matches only numbers, it is technically not possible to inject anything.
    //However best practices are going to be "always bind".
    $q=$db->prepare("select Gal_ID, Image from images where Gal_ID in (".implode(',', $matches[1]).")");
    $q->execute();

    //format the images into an array
    $images = array();
    while($r=$q->fetch(PDO::FETCH_ASSOC)){
        $images[$r['Gal_ID']][] = "<a href='gallery/large/{$r['Image']}' class='fancybox-thumbs' rel='gallery'><img src='gallery/thumb/{$r['Image']}'></a>";
    }

    //replace shortcode with images
    $result = preg_replace_callback('/\[gal=(\d+)\]/i', function($match) use ($images){
        if(isset($images[$match[1]])){
            return implode('', $images[$match[1]]);
        } else {
            return $match[0];
        }
    }, $string);

    echo $result;
}

我尽可能多地对其进行了测试,但我没有 PDO 和/或您的表格。这应该可以替代您上面的内容。

【讨论】:

  • 非常感谢,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2013-12-22
  • 2013-03-22
  • 1970-01-01
  • 2023-03-09
  • 2011-07-08
  • 2019-01-10
  • 2018-07-11
  • 2012-02-07
相关资源
最近更新 更多