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:
Subscribe to Total PHP: RSS | Email
Related Posts:
Recommended resources
Recent articles
- How to Read an RSS Feed with PHP 5
- Performing searches on strings using strpos
- PHP form validation basics
- Using a global configuration file
- Creating a text or csv file of information from your database
- Using an autoload function to make your life easier
- Choosing a PHP Web Host
- Why you will love PHP5

















There are no comments on this article yet
Please log in to post a comment about this article.