How to find an array of character occurrences in a string

I am looking for a function in PHP to return an array of character positions in a string.

Entering these parameters "hello world", "o" will return (4.7).

Thanks in advance.

+4
source share
4 answers

you can check it out http://www.php.net/manual/en/function.strpos.php#92849 or http://www.php.net/manual/en/function.strpos.php#87061 there are custom functions strpos to search for all occurrences

+2
source

No loop required

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

There is no such function (AFAIK) in PHP that does what you are looking for, but you can use preg_match_all to get the substring pattern offsets:

 $str = "hello world"; $r = preg_match_all('/o/', $str, $matches, PREG_OFFSET_CAPTURE); foreach($matches[0] as &$match) $match = $match[1]; list($matches) = $matches; unset($match); var_dump($matches); 

Output:

 array(2) { [0]=> int(4) [1]=> int(7) } 

Demo

+1
source
 function searchPositions($text, $needle = ''){ $positions = array(); for($i = 0; $i < strlen($text);$i++){ if($text[$i] == $needle){ $positions[] = $i; } } return $positions; } print_r(searchPositions('Hello world!', 'o')); 

will do.

0
source

Source: https://habr.com/ru/post/1390175/


All Articles