Twin Functions

Well, this was what I thought when I was first introduced to PHP. Almost every library function seemed to have a duplicate. But my title itself is wrong. They are not at all identical.

Take for instance

1) str_replace() and preg_replace()
2) join() and implode()
3) split(), preg_split() and explode()

But are they identical? NO. All these functions have their own uses and it is not good to use str_replace() when you actually need preg_replace() or use preg_replace() when a simple str_replace() would do.

Don’t get me? Well, I will explain.

Replace all occurrences of the search string with the replacement string

Perform a regular expression search and replace

Lets consider that I have a text called ‘Katie Holmes’. Now I want the ‘Holmes’ part of it to be replaced by ‘Cruise’ ;). Here, what function would you use ideally? A simple str_replace() would do here.

But lets say, I do not know the exact content of my text. It could be ‘katie holmes’ or ‘katieeee holmes’ or ‘KATIE HOLMES’. All I know here is that the name starts with kat and ends with holmes. So, str_replace can’t be used here as I do not know WHICH text to replace.
In this case, I would use preg_replace. The pattern would be /kati(.*?)holmes/is.

The rule of thumb is: If you know the EXACT text to be replaced, use str_replace. Otherwise, use preg_replace.

Some people try to use PREG for every other replace. This is redundant and not needed. Also, use PREG only if you know it well. The same theory is valid for all other functions too.

Let me know if you have any suggestions. Please feel free to comment.

Posted in PHP

2 thoughts on “Twin Functions

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s