PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

How do I find the last occurrence of a character in a string?


n PHP if you want to find the first occurrence of a character in a string, what function do you use? Answers on a postcard please.

Actually, to speed that up, the answer is strpos.

So if you want to find the LAST occurrence, then add another 'r', and you have yourself the function of choice: strrpos - we emphasise this as you will get confused if you miss out the second 'r' so always ensure that you put it in.

Here is the function in action:

<?php

$data 
"lets go backwards";

$lastr strrpos($data,"r");
echo 
"The last 'r' occurs at $lastr";
//The last 'r' occurs at 14
?>


And there you have it - we know the position of the last 'r' in there.

This function is useful for a range of reasons. Sometimes we will want to trim the string so that anything after the bit we're interested in disappears.

For instance, if you want to trim a long string of text down to, say, length 100 characters, but want to stop at the last time a space occurs, then this function is really useful.

It looks a bit naff if our data ends with something like "I was just sayi..." - we want it to end with "I was just..." so we end with full words.

This can be achieved with a combination of strrpos, strlen and substr - have a go and see if you can work out how to trim any string of data down so that is a set length, but always ends with a full word - this is really useful for creating meta tags and titles for instance on your dynamic web pages, so is worth working out!



Comment on this Question and Answer >>>

ASK A QUESTION

More strings PHP Questions

How do I break email address into username and hostname?

How do I remove trailing whitespace?

How do I find the length of a string in PHP?

How do I find the ASCII value of a string character?

How do I make the first letter of each word upper case?



Custom Search