38 lines
1.2 KiB
Plaintext
38 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
When a back reference in a regex refers to a capturing group that hasn't been defined yet (or at all), it can never be matched. Named back references throw a warning in that case; numeric back references fail silently when they can't match, simply making the match fail.
|
|
|
|
|
|
When the group is defined before the back reference but on a different control path (like in `(.)|\1` for example), this also leads to a situation where the back reference can never match.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,php]
|
|
----
|
|
preg_match("/\\1(.)/", $str); // Noncompliant, group 1 is defined after the back reference
|
|
preg_match("/(.)\\2/", $str); // Noncompliant, group 2 isn't defined at all
|
|
preg_match("/(.)|\\1/", $str); // Noncompliant, group 1 and the back reference are in different branches
|
|
preg_match("/(?<x>.)|\k<x>/", $str); // Noncompliant, group x and the back reference are in different branches
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,php]
|
|
----
|
|
preg_match("/(.)\\1/", $str);
|
|
preg_match("/(?<x>.)\\k<x>/", $str);
|
|
----
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
include::../highlighting.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|