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 position of a letter in a string in PHP?


Another common requirement in PHP is to be able to find where a particular letter, or indeed string, occurs within a string.

If we want to do this in things like Javascript you might be looking for a function called indexOf or similar.

In fact in PHP what you need to use is a function called strpos.

It works like this:

<?php

$data 
"hello world";

$whereisw strpos($data,"w");

echo 
"W occurs at $whereisw";
//W occurs at 6
?>


That is a very simple example and tells us where the letter 'w' first occurs in the string. This is an extremely useful function indeed so is well worth getting to grips with.

Note that it tells you the first occurrence so if the needle is there several times, and you want to count how many times it is there, or do something similar, then there are other methods out there for you, but see if you can work out how you could do this using strpos combined with your PHP knowledge too as a fun exercise!



Comment on this Question and Answer >>>

ASK A QUESTION

More strings PHP Questions

What is the usage of { } in string handling in php?

What is the usage of {} in strings?

What is the difference between ' and "?

How do we count paragraphs or newlines?

How do I calculate the MD5 hash of a string?



Custom Search