我收到语法错误,意外的 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 ).'"';
谁能帮我解决一下? 谢谢
最佳答案
您不能将“$2”作为变量名。它必须以字母或下划线开头。
http://php.net/manual/en/language.variables.basics.php
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
编辑 以上是我的原始答案,是对简单的“语法错误”问题的正确答案。下面有更深入的答案...
您正在尝试使用 $2 来表示“第二个捕获组”,但是此时您还没有做任何事情来匹配您的正则表达式。即使 $2 是一个有效的 PHP 变量名,它仍然不会在您的脚本中的那个位置设置。因此,您可以确定您使用的 preg_replace
不当,它可能不适合您的实际需要。
请注意 preg_replace
文档不支持在替换操作之外使用 $n 作为单独的变量。换句话说, 'foo' 。 1 美元。 'bar'
不是有效的替换字符串,但 'foo$1bar'
是。
根据 get_site_url
的复杂性,您有 2 个选择:
如果
get_site_url
只是添加根目录或服务器名称,您可以将替换字符串更改为src="/myotherlocation$2"
。这将有效地将 img src 中的“/image/...”替换为“/myotherlocation/image/...”。如果get_site_url
正在做一些更复杂的事情,这将不起作用。如果
get_site_url
很复杂,您应该使用preg_replace_callback
每other answers .如果您在实现过程中遇到问题,请阅读文档并发布新问题(或者我想更新这个问题?)。
关于php - 尝试将正则表达式匹配传递给函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9571559/