PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

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!



More strings PHP Questions

What is the difference between print and echo?
How do I convert characters to HTML entities using PHP?
How do I remove space from the start of a PHP string?
How do I convert relevant characters in a string to HTML entities?
How do you check if a variable is set or not in PHP?