user81993 user81993 - 6 months ago 22
PHP Question

PHP refusing this regular expression

So I'm trying to check for match and if match, extract a variable name out of a string. The variable name should be preceded by "$" and cannot be escaped with "\", so for example "$name" should extract "name" and "\$name" or "name" shouldn't match. Heres the command:

$match = preg_match("/^(?<!\\)(\$.*)$/", $potential, $name);


I constructed and tested it using regex101.com and it works there, however, I'm getting an error from PHP saying

"preg_match(): Compilation failed: missing ) at offset 13 in ..."

and I have no clue what its referring to.

Answer

My thought is that you will need to escape certain characters to consume the regular expression in PHP

$match = preg_match('/^(?<!\\\\)(\$.*)$/', $potential, $name);

Edit: the backslash is the escape character in both Regex and PHP, you will need to doubly escape the slashes.

Comments