A web developer’s diary

November 21, 2006

Twin Functions

Filed under: PHP — Celia @ 11:45 am

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.

STR_REPLACE:
Replace all occurrences of the search string with the replacement string

PREG REPLACE:
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.

Advertisements

2 Comments »

  1. exit() and die() are the same πŸ™‚

    Comment by draicone — November 22, 2006 @ 6:57 am | Reply

  2. Oh Yeah!! That goes without saying. πŸ™‚

    I saw your bitmeta site. Looks very promising. Will try to download the framework and see it.

    Comment by Bindu — November 22, 2006 @ 7:49 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Create a free website or blog at WordPress.com.

%d bloggers like this: