Error trying to pass regex match to function

后端 未结 5 1707
生来不讨喜
生来不讨喜 2021-01-19 13:03

I\'m getting Syntax error, unexpected T_LNUMBER, expecting T_VARIABLE or \'$\'

This is the code i\'m using

function wpse44503_filter_con         


        
5条回答
  •  Happy的楠姐
    2021-01-19 13:42

    You can't have '$2' as a variable name. It must start with a letter or underscore.

    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]*'

    Edit Above was my original answer and is the correct answer to the simple "syntax error" question. More in-depth answer below...

    You are trying to use $2 to represent "the second capture group", but you haven't done anything at that point to match your regex. Even if $2 was a valid PHP variable name, it still wouldn't be set at that point in your script. Because of this, you can determine that you are using preg_replace improperly and that it may not suit your actual needs.

    Note that the preg_replace documentation doesn't support using $n as a separate variable outside of the replacement operation. In other words, 'foo' . $1 . 'bar' is not a valid replacement string, but 'foo$1bar' is.

    Depending on the complexity of get_site_url, you have 2 options:

    1. If get_site_url is simply adding a root directory or server name, you could change your replacement string to src="/myotherlocation$2". This will effectively replace "/image/..." with "/myotherlocation/image/..." in the img src. This will not work if get_site_url is doing something more complex.

    2. If get_site_url is complex, you should use preg_replace_callback per other answers. Give the documentation a read and post a new question (or I guess update this question?) if you have trouble with the implementation.

提交回复
热议问题