开发者

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

开发者 https://www.devze.com 2023-03-28 15:28 出处:网络
How to find positions of a character in a string or sentence in php $char= \'i\'; $string = \'elvis williams\';

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消