Add to Favorites

php string replace vs regex

For all you budding php developers out there who are now experimenting with regular expressions and data clean up, I advise you think twice before using regex over a simple str_replace. If you are performing complex string replacements regex is the best choice and will give you a performance boost over using many str_replace ( and other functions ) in place of using one regular expression.

There have been tests showing that using multiple preg_replace functions in a row can perform better than using multiple str_replace in a row; they all have pretty much come down to showing that on a one to one basis ( one str_replace vs one preg_replace ) the performance goes to str_replace. This is because initializing the regex engine has a little overhead when you make the first call to use it.

Don't even get started with ereg_replace, the performance is worse nearly all the time and this function is set to be deprecated in future versions of php.

So it just goes to show, put a little thought into how you want to do your string replacements and it could pay off in applications that process a lot of data or a lot of users.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up