PHP的strchr
函數用于在字符串中查找第一次出現某個字符的位置
function find_multiple_chars($str, $chars) {
$positions = array();
foreach ($chars as $char) {
$pos = strpos($str, $char);
if ($pos !== false) {
$positions[] = $pos;
}
}
return $positions;
}
$str = "Hello, I am a PHP developer.";
$chars = array(',', '.');
$positions = find_multiple_chars($str, $chars);
print_r($positions);
這個示例中,我們定義了一個名為find_multiple_chars
的函數,它接受一個字符串和一個字符數組作為參數。然后,我們遍歷字符數組,使用strpos
函數查找每個字符在字符串中的位置,并將找到的位置添加到$positions
數組中。最后,返回$positions
數組。
在這個例子中,我們查找字符串"Hello, I am a PHP developer."
中的逗號,
和句點.
,輸出的結果將是:
Array
(
[0] => 5
[1] => 43
)
這表示逗號出現在位置5,句點出現在位置43。