user81993 user81993 - 2 years ago 84
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 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download