使用替换函数替换PREG_REPLACE

2022-03-22 00:00:00 php preg-replace

如何将preg_replace与函数一起用作替换参数?此代码出错。

function getInfo($id,$slot){
  if(!$id){ return '<b>Error</b> Id Not Returned. Please contact support@site.com for more information.'; }
  $mm = mysql_query("SELECT * FROM `users` WHERE `id`='".$id."'");
  $mma = mysql_fetch_assoc($mm);
  $p = $mma[$slot];
  return $p;
  //return $id; <- Debug (Returns ID given)
}
$post = preg_replace(
  "/[CallName]([^]]+)[/CallName]/", 
  getInfo('\1',"fullname"), 
  $post
);

解决方案

e修饰符现在deprecated支持preg_replace_callback。

示例用法:

$x = 'abcd-efg-hijk-lmnop';

$x = preg_replace_callback(
  '/-(.)/', //pattern
  function($matches) { //callback
    return strtoupper($matches[1]);
  }, 
  $x //subject
);

echo $x; //abcdEfgHijkLmnop

相关文章