Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find a array of occurence of a character in a string

Tags:

string

php

I am searching for a function in PHP to return the array of position of a character in a string.

Inputing those parameters "hello world", 'o' would return (4,7).

Thanks in advance.

like image 563
Pradip Avatar asked Dec 17 '22 05:12

Pradip


2 Answers

No looping needed

$str = 'Hello World';
$letter='o';
$letterPositions = array_keys(array_intersect(str_split($str),array($letter)));

var_dump($letterPositions);
like image 147
Mark Baker Avatar answered Mar 04 '23 03:03

Mark Baker


you can check this http://www.php.net/manual/en/function.strpos.php#92849 or http://www.php.net/manual/en/function.strpos.php#87061, there are custom strpos functions to find all occurrences

like image 28
boobiq Avatar answered Mar 04 '23 03:03

boobiq