尝试将正则表达式匹配传递给函数时出错 [英] Error trying to pass regex match to function

查看:45
本文介绍了尝试将正则表达式匹配传递给函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到语法错误,意外的 T_LNUMBER,需要 T_VARIABLE 或 '$'

这是我正在使用的代码

function wpse44503_filter_content( $content ) {
    $regex = '#src=("|\')'.
        '(/images/(19|20)(0-9){2}/(0|1)(0-9)/[^.]+\.(jpg|png|gif|bmp|jpeg))'.
        '("|\')#';
    $replace = 'src="'.get_site_url( $2 ).'"';

    $output = preg_replace( $regex, $replace, $content );

    return $output;
}

这是我遇到错误的那一行 $replace = 'src="'.get_site_url( $2 ).'"';

This is the line where i'm getting that error $replace = 'src="'.get_site_url( $2 ).'"';

谁能帮我解决这个问题?谢谢

Can anyone help me to fix it? Thanks

推荐答案

使用 preg_replace,你需要使用 preg_replace_callback 改为获取调用的函数每场比赛.

What you're trying to do (ie replacing the matched string with the result of a function call) can't be done using preg_replace, you'll need to use preg_replace_callback instead to get a function called for every match.

preg_replace_callback 的简短示例;

A short example of preg_replace_callback;

$get_site_url =                    // Returns replacement
  function($row) { 
    return '!'.$row[1].'!';        // row[1] is first "backref"
  };                                                     

$str = 'olle';
$regex = '/(ll)/';                 // String to match

$output = preg_replace_callback(   // Match, calling get_site_url for replacement
    $regex,
    $get_site_url,
    $str);

var_dump($output);                 // output "o!ll!e"

这篇关于尝试将正则表达式匹配传递给函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆