How to find position of a character in a string in PHP
Asked Answered
O

1

6

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..

Orgy answered 16/8, 2011 at 11:25 Comment(1)
Welcome to Stack Overflow. You can format source code with the {} toolbar button. (ajreal has done it for you this time.)Spodumene
B
17

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

Boa answered 16/8, 2011 at 11:26 Comment(1)
wow that saves my time..is there any possibility to rewrite the logic in recursive method??Orgy

© 2022 - 2024 — McMap. All rights reserved.