簡體   English   中英

如何在 PHP 中的字符串中查找字符的 position

[英]How to find position of a character in a string in PHP

如何在 php 中查找字符串或句子中字符的位置

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

我試過strpos ..但沒用..

這將為您提供 $string 中 $char 的 position:

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

如果您想要字符串中所有出現 $char 的 position:

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

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

print_r($result);

在這里測試它: http://codepad.viper-7.com/yssEK3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM