开发者

PHP RegExp Variable in Function

I'm using a Function to parse UBBC and I want to use a function to find data from a database to replace text (a [user] kind of function). However the code is ignoring the RegExp Variable. Is there any way I can get it to recognise the RegExp variable?

PHP Function:

function parse_ubbc($string){
    $string = $string;
    $tags = array(
        "user" => "#\[user\](.*?)\[/user\]#is"
    );
    $html = array(
        "user" => user_to_display("$1", 0)
    );
    return preg_replace($tags, $html, $string);
}

My function uses the username of the user to get their display name, 0 denotes that it is the username being used and can be ignored for the sake of this.

Any help would 开发者_Go百科be greatly appreciated.


You either rewrite your code to use preg_replace_callback, as advised.

Or your rewrite the regex to use the #e flag:

function parse_ubbc($string){
    $string = $string;
    $tags = array(
        "user" => "#\[user\](.*?)\[/user\]#ise"
    );
    $html = array(
        "user" => 'user_to_display("$1", 0)'
    );
    return preg_replace($tags, $html, $string);
}

For that it's important that PHP does not execute the function in the replacement array immediately. That's why you have to put the function call into 'user_to_display("$1", 0)' single quotes. So preg_replace executes it later with the #e flag.

A significant gotcha here is, that the username may never contain " double quotes which would allow the regex placeholder $0 to break up the evaluated function call (cause havoc). Hencewhy you have to rewrite the regex itself to use \w+ instead of .*?. Or again just use preg_replace_callback for safety.


You need to use preg_replace_callback if you want to source replacements from a database.


function parse_ubbc($string){
    $string = $string;
    function get_user_to_display($m){
        user_to_display($m[1], 0);
    }
    return preg_replace_callback('#\[user\](.*?)\[/user\]#is', 'get_user_to_display', $string);
}


You're calling user_to_display() with the string '$1', not the actual found string. Try:

function parse_ubbc($string){
    $string = $string;
    $tags = array(
        "user" => "#\[user\](.*?)\[/user\]#ise"
    );
    $html = array(
        "user" => 'user_to_display("$1", 0)'
    );
    return preg_replace($tags, $html, $string);
}

The changes are adding 'e' to the end of the regexp string, and putting the function call in quotes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜