代码之家  ›  专栏  ›  技术社区  ›  Niczem Olaske

带有功能切换错误的preg_replace(?)

  •  1
  • Niczem Olaske  · 技术社区  · 13 年前

    我正在尝试编写类似BB Code函数的东西,它将例如“[itemThumb type=file itemId=33]”替换为所选项目的缩略图。

    为此,我在uniText()中使用preg_replace:

    function universeText($str){
    
        $str = preg_replace("#\[itemThumb type=(.*)\ typeId=(.*)\]#", showChatThumb("$1","$2") , $str);
    return $str;
    
    
    }
    

    由于showChatThumb的输出不起作用,我将showChatThump()减少为:

    function showChatThumb($itemType, $itemId){
    switch($itemType){
    
       case 'file':
           $return = "rofl";
       break;
       case 'folder':
           $return = "lol";
       break;
       case 'link':
           $return = "asd";
       break;
    return $return;
    }
    

    但是switch()函数在某种程度上无法正确处理变量$itemId。当我在switch函数之前或之后定义$return时,它被向右传递并抛出了replace函数。 我读到这个开关有时不起作用,所以我也尝试了if,else if已经起作用了,但它也不起作用。

    但如果我这样写,也会通过replace函数返回正确的值:

    function showChatThumb($itemType, $itemId){
        return $itemType;
    }
    

    我现在真的一无所知,谢谢你的帮助

    1 回复  |  直到 13 年前
        1
  •  2
  •   Sudhir Bastakoti    13 年前

    尝试使用 preg_replace_callback() :

    function universeText($str){
        echo $str = preg_replace_callback("#\[itemThumb type=(.*)\ itemId=(.*)\]#", 'showChatThumb' , $str);
    }
    $str = "[itemThumb type=file itemId=33]";
    function showChatThumb($param){
    
        switch($param[1]){
    
          case 'file':
             $return = "rofl";
          break;
          case 'folder':
             $return = "lol";
          break;
          case 'link':
                $return = "asd";
          break;
    
        }
        return $return;
    }
    $tes = universeText($str);
    echo "<pre>"; print_r($tes);
    
    推荐文章