Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find position of a character in a string in PHP

Tags:

php

strpos

How to find positions of a character in a string or sentence in php

$char   = 'i';
$string = 'elvis williams';
$result = '3rd ,7th and 10th'.

I tried strpos..but no use..

like image 369
phpdeveloper Avatar asked Aug 16 '11 11:08

phpdeveloper


People also ask

How do you check a character is present in a string in PHP?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .

What is the strpos () function used for?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.


1 Answers

This will give you the position of $char in $string:

$pos = strpos($string, $char);

If you want the position of all occurences of $char in string:

$positions = array();
$pos = -1;
while (($pos = strpos($string, $char, $pos+1)) !== false) {
    $positions[] = $pos;
}

$result = implode(', ', $positions);

print_r($result);

Test it here: http://codepad.viper-7.com/yssEK3

like image 72
Arnaud Le Blanc Avatar answered Oct 20 '22 00:10

Arnaud Le Blanc