Skip to menu

Skip to content



Performing searches on strings using strpos

Wednesday, December 17th, 2008 at 4:37pm, in String Manipulation, written by Stefan Ashwell

There are occasions where you might want to search for a phrase within a string in PHP. Using the PHP function strpos we can do just this nice and easily.

It could be that you want to check to see if something exists within a string, maybe as part of some validation or as a conditional action. PHP enables to do this very simply and this can come in handy in all sorts of situations.

As an example, I want to see if the word "string" appears in a sentence.

$sentence = 'Using strpos we can find out if a string exists in another string';

if ( strpos($sentence, 'string') ) {
   // yes it does
} else {
   // no it doesn't
}

Obviously you can populate the sentence variable with database content within a loop or similar during practical applications.

Also quite handy in PHP 5 only is the stripos function, which works in exactly the same way, but is case insensitive. So as an example the following would still find a result, whereas when using strpos it does not:

$sentence = 'Using stripos we can find out if a String exists even though it has a capital letter in it';

if ( stripos($sentence, 'string') ) {
   // yes it does
} else {
   // no it doesn't
}

I hope you've found this article useful, if you have any comments don't hesitate to leave one!

Share and Enjoy:

  • bodytext
  • del.icio.us
  • Facebook
  • Google
  • Reddit
  • Technorati
  • Furl
  • StumbleUpon
  • NewsVine
  • Slashdot
  • Spurl
  • Ma.gnolia
  • Live
  • YahooMyWeb
  • E-mail this story to a friend!

Subscribe to Total PHP: RSS | Email

Related Posts:

- Generating Search Engine Friendly Titles for your URL

There are no comments on this article yet

Please log in to post a comment about this article.


Subscribe to our RSS Feed

Subscribe: RSS | Email

Clear Content - Easy to use PHP 5 Content Management System
CSS Contest

Recommended resources

Recent articles