PHP

php strchr函数的循环操作技巧有哪些

小樊
84
2024-08-10 06:36:34
栏目: 编程语言

  1. 使用while循环来查找字符串中的特定字符
$string = "Hello World";
$char = 'o';

$pos = 0;
while (($pos = strpos($string, $char, $pos)) !== false) {
    echo "Found $char at position $pos <br>";
    $pos++;
}
  1. 使用for循环来查找字符串中的特定字符
$string = "Hello World";
$char = 'o';

for ($i = 0; $i < strlen($string); $i++) {
    if ($string[$i] == $char) {
        echo "Found $char at position $i <br>";
    }
}
  1. 使用foreach循环来查找字符串中的特定字符
$string = "Hello World";
$char = 'o';

$chars = str_split($string);
foreach ($chars as $key => $value) {
    if ($value == $char) {
        echo "Found $char at position $key <br>";
    }
}

0
看了该问题的人还看了