(PHP 5, PHP 7, PHP 8)
stripos — 大文字小文字を区別せずに文字列が最初に現れる位置を探す
haystack
検索対象の文字列。
needle
検索する文字列。
PHP 8.0.0 より前のバージョンでは、needle
が文字列でない場合、
数値に変換され、文字のコードポイントとして扱われていました。
この振る舞いは PHP 7.3.0 以降では推奨されないので、
この機能を使用しないことを強く推奨します。
意図する動作に応じて、
needle
を string に明示的にキャストするか、
明示的に chr() 関数を呼び出すべきでしょう。
offset
指定すると、文字列内での検索開始位置がその位置になります。 負の数を指定すると、文字列の末尾からこの数だけ戻った場所から検索を開始します。
needle が見つかった位置を、
haystack
文字列の先頭 (offset の値とは無関係) からの相対位置で返します。
文字列の開始位置は 0 であり、1 ではないことに注意しましょう。
needle が見つからない場合は false
を返します。
バージョン | 説明 |
---|---|
8.2.0 | ケースフォールディングは、setlocale() で設定されたロケールに依存しなくなりました。 ASCII のケースフォールディングのみが行われます。 ASCII でないバイト列は、バイト値として比較されます。 |
8.0.0 |
needle は、空文字列を受け入れるようになりました。
|
8.0.0 |
needle に数値を渡すことはサポートされなくなりました。
|
7.3.0 |
needle に数値を渡すことは非推奨になりました。
|
7.1.0 |
負の offset をサポートするようになりました。
|
例1 stripos() の例
<?php
$findme = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';
$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);
// いいえ、'a' は明らかに 'xyz' の中には存在しません
if ($pos1 === false) {
echo "The string '$findme' was not found in the string '$mystring1'", PHP_EOL;
}
// !== を使用していることに注意しましょう。単に != としても期待通りに動作
// しません。なぜなら 'a' は 0 番目(最初) の文字だからです。
if ($pos2 !== false) {
echo "We found '$findme' in '$mystring2' at position $pos2", PHP_EOL;
}
?>
注意: この関数はバイナリデータに対応しています。
I found myself needing to find the first position of multiple needles in one haystack. So I wrote this little function:
<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
foreach($needles as $needle) {
$found[$needle] = stripos($haystack, $needle, $offset);
}
return $found;
}
// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
array(3) {
["fox"]=>
int(16)
["dog"]=>
int(40)
["."]=>
int(43)
["duck"]=>
bool(false)
}
*/
?>
Unlike strpos() it seems that stripos() does NOT issue a WARNING if the needle is an empty string ''.
Finding numbers in strings requires you to cast the number to string first.
strpos("123", 2) !== strpos("123", "2")
Regarding the === note, it might be worth clarifying that the correct tests for a binary found/not found condition are !==false to detect found, and ===false to detect not found.
Regarding the function by spam at wikicms dot org
It is very bad practice to use the same function name as an existing php function but have a different output format. Someone maintaining the code in the future is likely to be very confused by this. It will also be hard to eradicate from a codebase because the naming is identical so each use of stripos() would have to be analyzed to see how it is expecting the output format (bool or number/bool).
Calling it string_found() or something like that would make a lot more sense for long-term use.