rspec/rules/S5361/php/rule.adoc

33 lines
1.2 KiB
Plaintext
Raw Normal View History

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 its 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 doesnt contains special regex character or pattern.
== Noncompliant Code Example
----
$str = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
$changed = preg_replace_all("Bob is", "It's", $str); // Noncompliant
$changed = preg_replace_all("\.\.\.", ";", $changed); // Noncompliant
----
== Compliant Solution
----
$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:
----
$str = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
$changed = preg_replace_all("\w*\sis", "It's", $str);
$changed = preg_replace_all("\.{3}", ";", $changed);
----