Php preg_替换为功能开关错误(?)

Php preg_替换为功能开关错误(?),php,preg-replace,Php,Preg Replace,我正在尝试编写类似BB代码的函数,它用所选项目的缩略图替换例如“[itemThumb type=file itemId=33]” 为此,我在uniText()中使用preg_replace: 由于showChatThumb的输出不起作用,我将showChatThumb()缩减为: 但是switch()函数在变量$itemId中无法正常工作。当我在switch函数之前或之后定义$return时,它被传递给replace函数。 我读到开关有时不能正常工作,所以我也尝试了if,else if,但它也不

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

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

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

但是switch()函数在变量$itemId中无法正常工作。当我在switch函数之前或之后定义$return时,它被传递给replace函数。 我读到开关有时不能正常工作,所以我也尝试了if,else if,但它也不能工作

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

function showChatThumb($itemType, $itemId){
    return $itemType;
}
我现在真的不懂了,谢谢你的帮助

尝试使用:

函数universeText($str){
echo$str=preg\u replace\u回调(“\\[itemThumb类型=(.*)\itemId=(.*)\]\”,'showChatThumb',$str);
}
$str=“[itemThumb type=file itemId=33]”;
函数showChatThumb($param){
开关($param[1]){
案例“档案”:
$return=“rofl”;
打破
案例“文件夹”:
$return=“lol”;
打破
“链接”案例:
$return=“asd”;
打破
}
return$return;
}
$tes=universeText($str);
回声“;印刷费($tes);

我怀疑您是否可以将函数实际用作
preg_replace()
$replacement
参数它是有效的,但不知怎的,函数内部处理的变量是愚弄的,我希望函数是以空字符串作为参数调用的,并且返回值(将是
null
)由
preg\u replace()
函数使用。您可以使用
开关()
中的
默认操作来检查这一点<代码>preg_replace_callback()
,正如Sudhir所建议的那样,这似乎是一种更好的方法。我尝试只传递抛出函数的字符串,疯狂的是,如果说函数输出应该是$type和$typeId,它就可以工作。但是当我开始使用变量$type做任何事情时,它就不再工作了。你保存了我的脚本!非常感谢你!
function showChatThumb($itemType, $itemId){
switch($itemType){

   case 'file':
       $return = "rofl";
   break;
   case 'folder':
       $return = "lol";
   break;
   case 'link':
       $return = "asd";
   break;
return $return;
}
function showChatThumb($itemType, $itemId){
    return $itemType;
}
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);