我正试图写一些像BB-Code函数,它取代eg。"[itemThumb type=file itemId=33]",显示所选项目的缩略图。
为此,我使用preg_replace在uniText():
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函数。我读到这个开关有时不能正常工作,所以我也尝试了如果,否则如果已经,但它也不起作用。
但是如果我这样写的话,正确的值也会通过replace函数返回:
function showChatThumb($itemType, $itemId){
return $itemType;
}
我现在真的很笨,谢谢你的帮助
try using 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);