Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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...

Well ereg_replace() is deprecated as of PHP 5.3.0, so I wouldn't advise using it.

str_replace() or preg_replace() would be the logical alternatives. Personally I'd use str_replace() for a simple search/replace; preg_replace for anything more complex than simple matches

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top