String Position

Now, we dive into the world of strings and all of the crazy functions. Well, not exactly, but we will actually dive into a few of the really major string functions so that you have an understanding of how to work with strings in PHP. You might notice that PHP has a lot of functions and not methods, which means you can’t call something like string.method for these functions. First, we will start off with using the string position function in PHP. Example, please!

Example

Result

4

The result you get should be 4, unless I failed you. Upon an examination of this code, we see that we have a string variable that has the contents “The meerkat clan was victorious.” We then echo the result of our strpos function. Our strpos function takes $myString and searches for our next parameter, “meerkat”, beginning from our starting index of 0. If we count out the string, T is 0, h is 1, e is 2, the space is 3, and we have the word meerkat that starts at a position of 4. String position can be used this way, but it is often used with some other function like when you watch to get a part of a string when using the substr function.

Sometimes, you might use strpos to have an easy way to check if something is in a string. While not the most ideal function to use, it does the trick. We know the strpos function returns the index of the match, but what happens when it doesn’t find a match? In that case, it returns -1, so we can create an if statement that has a conditional checking if the strpos function returns something greater than -1.

I should mention a few things before we close this tutorial. The strpos function is case-sensitive, which means if I would have searched for “MEERKAT”, it have returned a negative one, which means it didn’t find a match. Also, the 0 we have is an optional parameterthat tells our search were to begin in the string. So, if we would have had 10 instead of 0, we wouldn’t have returned anything either. This is because “meerkat” begins on the index of 4. You can use this argument to get sub strings between certain words. Enough with PHP’s string position. Bring on the next string function!

strpos vs strrpos

Often, we assume that strpos and strrpos are the same. Well, the do the same function, but they approach it two different ways. strpos finds the first occurrence of the matching item in the string and returns its position in the string. strrpos starts from the end and returns the position of the last occurrence in the string.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.