Can anyone explain the difference in a real life situation between strpos() and strstr()?

Posted on 2011-09-17
Last Modified: 2012-05-12
Can anyone explain the difference in a real life situation between strpos() and strstr()?
Question by:Octalys
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
LVL 12

Expert Comment

ID: 36553381
LVL 12

Accepted Solution

jet-black earned 500 total points
ID: 36553395
You can also see by example:

$text = 'string';

The result of
echo strpos($text, 'ri');

Open in new window

On the other hand, the result of
echo strstr($text, 'ri');

Open in new window

strpos will give you position of the the text part you search.
strstr will give you the substring of the text started by the position of the the text part you search (which is equal to strpos() func.'s value) to the final character.
LVL 12

Expert Comment

ID: 36553413
So, if you only check if the text part exists in the string, just use strpos() function. It is faster.

There will be times when you will need the strstr() function too.
Here's the example code from the manual:

$email  = '';
$domain = strstr($email, '@');
echo $domain; // prints

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name

Open in new window


Author Closing Comment

ID: 36553706
thanks for the answer.
I was looking at the php documentation of both functions, but somehow I couldnt find the difference. Now I see it.

Make sense.

LVL 12

Expert Comment

ID: 36553713
You're welcome.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question