Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, what is the better choice for removing a known string?

I am looking to search for and replace a known string from within another string. Should I use str_replace() or preg_replace()? The string to be replaced would be something similar to [+qStr+], [+bqID+], or [+aID+] and it would be being searched for in a code chunk similar to this:

<li> [+qStr+]
   <ol class="mcAlpha">
       <li><input type="radio" name="[+bqID+]" id="[+bqID+]_[+aID+]" value="[+aID+]" /><label for="[+bqID+]_[+aID+]">[+aStr+]</label></li>
   </ol>
</li>

I would be replacing the strings with the results from a MySQL query, and be performing this action or similar up to 200 times at a time. Which function str_replace() or preg_replace() would be the easiest and/or quickest method to take.

like image 756
Brook Julias Avatar asked Jun 14 '10 14:06

Brook Julias


2 Answers

If your string is fixed, and you don't need regular expressions, always use str_replace, as it will be faster. Note moreover that you should forget about ereg_replace, and always use preg_replace, as the former has been deprecated.

like image 106
Palantir Avatar answered Sep 24 '22 19:09

Palantir


if you know the string and don't need regular expressions, use str_replace(). it's faster because it doesn't need to try if you use a regex.

PS: for regex you should use preg_replace() instead of ereg_replace(), just for the future...

like image 33
oezi Avatar answered Sep 20 '22 19:09

oezi