rspec/rules/S5361/php/rule.adoc

33 lines
1.2 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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("/Bob is/", "It's", $str); // Noncompliant
$changed = preg_replace("/\.\.\./", ";", $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("/\w*\sis/", "It's", $str);
$changed = preg_replace("/\.{3}/", ";", $changed);
----