1

我正在尝试编写类似 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 的输出不起作用,我将 showChatThumb() 减少为:

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 already 但它也不起作用。

但是如果我这样写,也将返回正确的值并抛出替换函数:

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

我现在很无能为力,谢谢大家的帮助

4

1 回答 1

2

尝试使用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);
于 2013-04-12T07:54:37.840 回答