php - 尝试将正则表达式匹配传递给函数时出错

标签 php regex preg-replace syntax-error

我收到语法错误,意外的 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 个选择:

  1. 如果 get_site_url 只是添加根目录或服务器名称,您可以将替换字符串更改为 src="/myotherlocation$2"。这将有效地将 img src 中的“/image/...”替换为“/myotherlocation/image/...”。如果 get_site_url 正在做一些更复杂的事情,这将不起作用。

  2. 如果 get_site_url 很复杂,您应该使用 preg_replace_callbackother answers .如果您在实现过程中遇到问题,请阅读文档并发布新问题(或者我想更新这个问题?)。

关于php - 尝试将正则表达式匹配传递给函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9571559/

相关文章:

匹配所有无序数字序列的正则表达式

mysql - 预替换 : capturing single quote inside single quote escaped expression

php - 两个不同主机的上传目录

javascript - JQuery 验证禁用按钮,直到所有字段都处于事件状态,但每次按键时不应显示错误

php - file_get_contents 对 'https://en.wikipedia.org/wiki/Category:Upcoming_singles' 的变量响应

Python re.findall() 不会终止

php - 在 php :7. 4-fpm 镜像上安装 PHP-zip

javascript - 正则表达式匹配较长的项目

php - 使用关联数组替换字符串中的几个单词,保持原始大小写不变

PHP preg_replace url 字符串