rspec/rules/S6323/php/rule.adoc

35 lines
1.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
include::../description.adoc[]
=== Noncompliant code example
2022-02-04 17:28:24 +01:00
[source,php]
----
preg_match("/Jack|Peter|/", "John"); // Noncompliant - returns 1
preg_match("/Jack||Peter/", "John"); // Noncompliant - returns 1
----
=== Compliant solution
2022-02-04 17:28:24 +01:00
[source,php]
----
preg_match("/Jack|Peter/", "John"); // returns 0
----
=== Exceptions
2023-01-11 14:32:28 +02:00
One could use an empty alternation to make a regular expression group optional. Note that the empty alternation should be the first or the last within the group, or else the rule will still report.
[source,php]
----
2023-01-11 14:32:28 +02:00
preg_match("/mandatory(|-optional)/", "mandatory"); // returns 1
preg_match("/mandatory(-optional|)/", "mandatory-optional"); // returns 1
----
However, if there is a quantifier after the group the issue will be reported as using both `|` and quantifier is redundant.
[source,php]
----
preg_match("/mandatory(-optional|)?/", "mandatory-optional"); // Noncompliant - using both `|` inside the group and `?` for the group.
----
include::../implementation.adoc[]