rspec/rules/S5361/php/rule.adoc

38 lines
1.3 KiB
Plaintext

== Why is this an issue?
An `preg_replace` call always performs an evaluation of the first argument as a regular expression, even if no regular expression features were used. This has a significant performance cost and therefore should be used with care.
When `preg_replace` is used, the first argument should be a real regular expression. If it's not the case, `str_replace` does exactly the same thing as `preg_replace` without the performance drawback of the regex.
This rule raises an issue for each `preg_replace` used with a simple string as first argument which doesn't contains special regex character or pattern.
=== Noncompliant code example
[source,php]
----
$str = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
$changed = preg_replace("/Bob is/", "It's", $str); // Noncompliant
$changed = preg_replace("/\.\.\./", ";", $changed); // Noncompliant
----
=== Compliant solution
[source,php]
----
$str = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
$changed = str_replace("Bob is", "It's", $str);
$changed = str_replace("...", ";", $changed);
----
Or, with a regex:
[source,php]
----
$str = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
$changed = preg_replace("/\w*\sis/", "It's", $str);
$changed = preg_replace("/\.{3}/", ";", $changed);
----