Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace with strpos?

The str_replace function with a strpos checking can avoid extra work?

METHOD 1

...
if (strpos($text, $tofind) !== FALSE)
 $text = str_replace($tofind, $newreplace, $text);
...

METHOD 2

...
$text = str_replace($tofind, $newreplace, $text);
...

Question: This two methods works but... I want know if strpos-checking (or other) is good way or a bad, useless (and optimization antipattern).

like image 533
Manz Avatar asked Dec 22 '22 07:12

Manz


1 Answers

You may save some str_replace() calls, but you get always additional strpos()-calls and !== false comparisons. However, I don't think, that it will make any measureable impact, as long as this code will not run around 100000 times (or such). Thus as long as you don't need to know, if there are replacements to made, you should avoid this "optimization" to keep things more simple and readable.

like image 188
KingCrunch Avatar answered Dec 24 '22 00:12

KingCrunch