So I am new to regular expressions and I am attempting to write one that will allow me to replace an apostrophe (') with \'. The regex that I came up with worked with all my test cases when I tested it on http://myregextester.com, but completely error out when I implement it in my code.
Anyways, this is what I have as of yet:
preg_replace('/((?<!\\)\'+(?=\d\ds\b))|(\b(?<=\w)(?<!\\)\'+(?=\w+\b))/','\'',$text);
and it throws this error:
A PHP Error was encountered
Severity: Warning
Message: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 50
I have counted like twenty times to see where the ) is not matching up, and to my eyes there is not. Here is one of my several counts:
( ( ?<!\\ )'+ ( ?=\d\ds\b ) ) | ( \b ( ?<=\w ) ( ?<!\\ ) '+ ( ?=\w+\b ) )
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Any ideas, or pointing out my glaringly obvious mistakes a newbie can’t spot would be much appreciated.
\\)in a string literal becomes\)– escaped closing parenthesis – in a regex pattern, as double backslash sequence is interpolated into a single backslash even within the string literal delimited by single quotation marks. The problem is, though, that\)sequence in regex pattern is used to represent a literal)symbol (which will otherwise be parsed as a metacharacter).What you intend to do is probably best written with
\\\\). This way each\\sequence in a string literal becomes a single\in the pattern. The pattern parser will see this:\\)… a literal backslash symbol, followed by
)metacharacter.But it seems to be there’s another problem here: in your regex you’re looking for some special (a series) of apostrophes, yet replace them with single apostrophe again. Remember,
\'within a string literal is just that – single quotation mark! You probably meant to use'\\\''here instead.