开发者

Code working only PHP 5.3.6 [duplicate]

开发者 https://www.devze.com 2023-03-14 14:29 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Anonymous functions pre PHP 5.3.0
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Anonymous functions pre PHP 5.3.0

I have this code:

$bbcode = 'Users [user=1], [user=2] and [user=3] are friendly.';
echo preg_replace_callback(
            '#\[user=(\d+)\]#',
            function($matches) {
                $userName = getUserNameByUserId($matches[1]);
                return "<a href=user.php?id=$matches[1]>$us开发者_开发知识库erName</a>";
            },
            $bbcode
        );

And it's working only for the last PHP version. I want to make it work for PHP 5.2.17.


Yes you can:

function callback_function($matches) {
  $userName = getUserNameByUserId($matches[1]);
  return "<a href=user.php?id=$matches[1]>$userName</a>";
}

$bbcode = 'Users [user=1], [user=2] and [user=3] are friendly.';
echo preg_replace_callback(
            '#\[user=(\d+)\]#',
            'callback_function',
            $bbcode
);

The function needs to be defined slightly different for PHP 5.2.x, so define it prior calling pre_replace_callback. Then provide it's name in form of a string.

Probably you can additionally upgrade the PHP version on the host where you want to run the code. PHP 5.3 is much faster then PHP 5.2 which is out of live even.


Anonymous functions were introduced in version 5.3, so that code will only work in 5.3 and up.


If you want a much simpler construction:

echo "Users ";
echo "<a href=\"user.php?id=1\">" . getUserNameByUserId(1) . "</a>";
echo ", ";
echo "<a href=\"user.php?id=2\">" . getUserNameByUserId(2) . "</a>";
echo " and ";
echo "<a href=\"user.php?id=3\">" . getUserNameByUserId(3) . "</a>";
echo " are friendly.";


You can use the 'e' option of preg_replace as an alternative.

echo preg_replace('#\[user=(\d+)\]#e','"<a href=\"user.php?id=$1".getUserNameByUserId($1)."</a>"',$bbcode);
0

精彩评论

暂无评论...
验证码 换一张
取 消