How do I find the position of a letter in a string in PHP?
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?
