stripos

(PHP 5, PHP 7, PHP 8)

stripos大文字小文字を区別せずに文字列が最初に現れる位置を探す

説明

stripos(string $haystack, string $needle, int $offset = 0): int|false

文字列 haystack の中で needle が最初に現れる位置を探します。

strpos() と異なり、stripos() は大文字小文字を区別しません。

パラメータ

haystack

検索対象の文字列。

needle

検索する文字列。

PHP 8.0.0 より前のバージョンでは、needle が文字列でない場合、 数値に変換され、文字の通常の値として扱われていました。 この振る舞いは PHP 7.3.0 以降では推奨されないので、 この機能を使用しないことを強く推奨します。 意図した動作に依存する場合、 needle を string に明示的にキャストするか、 明示的に chr() 関数を呼び出すべきでしょう。

offset

指定すると、文字列内での検索開始位置がその位置になります。 負の数を指定すると、文字列の末尾からこの数だけ戻った場所から検索を開始します。

戻り値

needle が見つかった位置を、 haystack 文字列の先頭 (offset の値とは無関係) からの相対位置で返します。 文字列の開始位置は 0 であり、1 ではないことに注意しましょう。

needle が見つからない場合は false を返します。

警告

この関数は論理値 false を返す可能性がありますが、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'";
}

// === を使用していることに注意しましょう。単に == としても期待通りに動作
// しません。なぜなら 'a' は 0 番目(最初) の文字だからです。
if ($pos2 !== false) {
echo
"We found '$findme' in '$mystring2' at position $pos2";
}
?>

注意

注意: この関数はバイナリデータに対応しています。

参考

  • mb_stripos() - 大文字小文字を区別せず、 文字列の中で指定した文字列が最初に現れる位置を探す
  • str_contains() - 指定された部分文字列が、文字列に含まれるかを調べる
  • str_ends_with() - 文字列が、指定された文字列で終わるかを調べる。
  • str_starts_with() - 文字列が指定された部分文字列で始まるかを調べる
  • strpos() - 文字列内の部分文字列が最初に現れる場所を見つける
  • strrpos() - 文字列中に、ある部分文字列が最後に現れる場所を探す
  • strripos() - 文字列中で、特定の(大文字小文字を区別しない)文字列が最後に現れた位置を探す
  • stristr() - 大文字小文字を区別しない strstr
  • substr() - 文字列の一部分を返す
  • str_ireplace() - 大文字小文字を区別しない str_replace

add a note add a note

User Contributed Notes 8 notes

up
39
emperorshishire at gmail dot com
15 years ago
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)
   }
*/
?>
up
3
sorrynorealemail at example dot com
5 years ago
Unlike strpos() it seems that stripos() does NOT issue a WARNING if the needle is an empty string ''.
up
3
spam at kleppinger dot com
9 years ago
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.
up
1
Ian Macdonald
8 years ago
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.
up
0
emanuel dot karlsson at rolfsbuss dot se
5 years ago
Finding numbers in strings requires you to cast the number to string first.

strpos("123", 2) !== strpos("123", "2")
up
-14
steve at opilo dot net
10 years ago
A handy function if you need to adjust layout based on whether or not a string contains descending letters:

<?php function containsDescenders($text) {
   
$descenders = array("g","j","p","q","y");
    foreach (
$descenders as $letter) {
        if (
stripos($text,$letter) !== false) {
            return
true;
        }
    }
    return
false;
}
?>
up
-20
spam at wikicms dot org
10 years ago
If you like using ternary operator, I wrote simple example how to use stripos function.
Also, in my example I add "How to use namespaces" for wide knowledges for newbies.

<?php
namespace My;

//You can be free using core functions in your NameSpaces (My)
function stripos($haystack, $needle) {
   
//To call core function (from global NS) you should add backslash only - \func
   
return (FALSE === \stripos($haystack, $needle)) ? FALSE : TRUE;
}

var_dump(stripos($haystack = 'John knows English language.', $needle = 'john')); //TRUE
var_dump(stripos($haystack = 'Sara knows English language too.', $needle = 'john')); //FALSE
?>
up
-21
grf at post dot cz
16 years ago
this would to work with any language, i hope.
tested on czech (eastern europe) lang.

<?php
/****************************************
*    SAFE HIGHLIGHT
****************************************/
/**
* function finds and encase every string in a $needleArr array with
* strings $shearLft (from the left side) and $shearRgt (guess from which
* side).
* already encased needles are IGNORED for any other step, so order
* of needles in $needleArr is pretty important.
*
* function is searching needles in case-insensitive mode,
* but case in the subject is saved.
*
* can you do it better? so, do it.
*
* @param array $needleArr array of needles
* @param string $shearLft left shear
* @param string $shearRgt right shear
* @param string $subject subject
* @param string $encoding encoding ('utf-8' is default)
*
* @author griffin
*/
function safeHighlight( $needleArr, $shearLft, $shearRgt, $subject, $encoding = 'utf-8')
{
   
   
// encoding
   
$e = $encoding;
   
   
// oh, no needles
   
if( !is_array( $needleArr))
        return
$subject;
       
   
// empty keys throw-off, only unique, reindex
   
$nA = array_values(
           
array_unique(
               
array_diff( $needleArr, array(''))
            )
        );
   
   
// needle count
   
if( !($nC = count( $nA)))
        return
$subject; // nothing to hl
       
    // shear length
   
if( !(($rLL = mb_strlen( $rL = $shearLft, $e))
    + (
$rRL = mb_strlen( $rR = $shearRgt, $e))))
        return
$subject; // no shears
   
    // subject length
   
if( !($sL = mb_strlen( $s = $subject, $e)))
        return
null; // empty subject
       
    // subject in lowercase (we need to aviod
    // using mb_stripos due to PHP version)
   
$sW = mb_strtolower( $s, $e);
   
   
// masking ~ 0=not changed, 1=changed
   
$m = str_repeat( '0', $sL);
   
   
// loop for each needle
   
for( $n=0; $n<$nC; $n++)
    {
       
       
// needle string loWercase
       
$nW = mb_strtolower( $nA[ $n], $e);
       
       
$o = 0; // offset
       
$nL = mb_strlen( $nW, $e); // needle length

        // search needle
       
while( false !== ($p = mb_strpos( $sW, $nW, $o, $e)))
        {
           
// oh hurrey, needle found on $p position
           
            // is founded needle already modified? (in full-length)
           
for( $q=$p; $q<($p+$nL); $q++)
                if(
$m[ $q])
                {
                   
// ai, caramba. already modified, jump over
                   
$o+= $nL;
                   
                   
// continue for while() loop - not for for() loop!
                   
continue 2;
                }
           
           
// explode subject and mask into three parts
            // partA|needle|partB
           
$sE[0] = mb_substr( $s, 0, $p, $e);
           
$sE[1] = mb_substr( $s, $p, $nL, $e);
           
$sE[2] = mb_substr( $s, $p+$nL, $sL-$p-$nL, $e);
           
           
// mask
            // partA|partB (needle not needed)
           
$mE[0] = mb_substr( $m, 0, $p, $e);
           
$mE[1] = mb_substr( $m, $p+$nL, $sL-$p-$nL, $e);
           
           
// apply shears
           
$sE[1] = $rL.$sE[1].$rR;
           
           
// update sunject length
           
$sL+= $rLL + $rRL;
           
           
// update mask
           
$m = $mE[0] . str_repeat( '1', $rLL + $nL + $rRL) . $mE[1];
           
           
// implode into a subject
           
$s = implode( $sE);
           
           
// update lowercase subject
           
$sW = mb_strtolower( $s, $e);
           
           
// increase offset
           
$o+= $rLL + $nL + $rRL;
           
           
// end of string reached
           
if( $o>=$sL)
                break;
           
        }
// while()
       
   
} // for( $n=0; $n<$nC; $n++)
   
    // oouu yeaaa, kick the subject out of the function
   
return $s;
   
}
// function safeHighlight()
/****************************************
*    END: SAFE HIGHLIGHT
****************************************/
?>
To Top