1

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

right so escape for both regex and for the string format in php?
Yes precisely, backslash is the escape character for both PHP and Regex
0

You've escaped a bracket:

preg_match('/^(?<!\\) <----HERE

FYI you can use several other delimiters to make your regex's more readable. Because so often we have slashes and escaped chars, then using '/' makes it hard to read. Consider using '#' or '~' or even '@' to increase readability.

Also reL your online regex tool of choice, it depends on which regular expression implementation (and version) the service uses, as to how accurate your results. I always use rubular.com (Uses PCRE) but for PHP you can use phpliveregex.com

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.