preg_replace with replacement function

2019-06-13 22:57发布

How do you use preg_replace with a function as the replacement parameter? I'm getting an error with this code.

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
);

2条回答
Summer. ? 凉城
2楼-- · 2019-06-13 23:26

I think you forgot e modifier (PREG_REPLACE_EVAL) in preg_replace function, this modifier is needed to evaluate replacement string as PHP code. It should be like this:

$post = preg_replace('~\[CallName\]([^]]+)\[/CallName\]~e', 'getInfo("$1", "fullname")', $post);

See this manual for for details.

查看更多
forever°为你锁心
3楼-- · 2019-06-13 23:39

The e modifer is now deprecated in favor of preg_replace_callback.

Sample usage:

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

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

echo $x; //abcdEfgHijkLmnop
查看更多
登录 后发表回答