Rule S5361 "str_replace should be preferred to preg_replace" cannot be used when using $limit

Please provide

  • Operating system: Linux/PHPStorm
  • SonarLint plugin version: 7.3.0.59206
  • Programming language you’re coding in: PHP
  • Is connected mode used: No

The rule suggests replacing preg_replace with str_replace. But that’s not always possible.

preg_replace('/_/', '/', 'some_string_with_many_underlines', 1);
// some/string_with_many_underlines

str_replace('_', '/', 'some_string_with_many_underlines');
// some/string/with/many/underlines

the fourth param of preg_replace is $limit. In the example above I want to replace just the first underline and not all of them.

1 Like

Hi @rcapile,

Welcome to the community and thank you for your report.
I’ve created a ticket to address this issue.
We will try to fix the rule in the next iteration.

Best,

1 Like