简体   繁体   English

这个PHP函数有什么问题

[英]What is wrong with this PHP function

I am new to PHP and regular expression. 我是PHP和正则表达式的新手。 I was going thorugh some online examples and came with this example: 我正在通过一些在线示例,并附带以下示例:

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>

in php.net but to my surprise it does not work and keep getting error: php.net但令我惊讶的是它不起作用,并不断出现错误:

PHP Parse error:  parse error, unexpected T_FUNCTION

Why get error ? 为什么会出错?

You are using PHP's Anonymous functions : functions that have no name . 您正在使用PHP的Anonymous函数没有name的函数。

When I run your program I get no error. 当我运行您的程序时,没有任何错误。 May be you are trying it on a PHP < 5.3 . 可能是您在PHP < 5.3上尝试了它。

Anonymous functions are available since PHP 5.3.0. 自PHP 5.3.0起提供匿名功能。

If PHP version is creating the problem you can re-write the program to not use Anonymous functions as: 如果PHP版本造成了问题,您可以重新编写程序以不使用匿名函数,如下所示:

<?php

// a callback function called in place of anonymous function.
echo preg_replace_callback('~-([a-z])~','fun', 'hello-world');

// the call back function.
function fun($match) {
    return strtoupper($match[1]);
}

?>

This example is for PHP 5.3. 本示例适用于PHP 5.3。 You probably use something older (eg, PHP 5.2). 您可能使用了较旧的版本(例如,PHP 5.2)。

Try this instead: 尝试以下方法:

<?php
function callback($match) {
    return strtoupper($match[1]);
}
echo preg_replace_callback('~-([a-z])~', 'callback', 'hello-world');

Are you using a version prior to PHP 5.3.0? 您使用的是PHP 5.3.0之前的版本吗? Anonymous functions are not supported in versions prior to that one. 在该版本之前的版本中,不支持匿名功能

You can check your version with a phpinfo page. 您可以使用phpinfo页面检查您的版本。

This should work on pre-5.3 versions: 这应该适用于5.3之前的版本:

echo preg_replace_callback(
        '/-([a-z])/',     
        create_function( '$arg', 'return strtoupper($arg[1]);' ),
        'hello-world'
     );

Regards 问候

rbo 机器人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM