PHP Velho Oeste 2024

mb_strpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strpos文字列の中に指定した文字列が最初に現れる位置を見つける

説明

mb_strpos(
    string $haystack,
    string $needle,
    int $offset = 0,
    ?string $encoding = null
): int|false

ある文字列の中で別の文字列が最初に現れる位置を見つけます。

マルチバイト文字列に正しくマッチするように strpos() を拡張したもので、 最初の 1 文字目の位置が 0 、2 文字目の文字が 1 というようになります。

パラメータ

haystack

調べたい文字列。

needle

haystack の中から探す文字列。 strpos() とは違い、 数値を指定しても文字コードの値と見なされることはありません。

offset

検索オフセット。 指定されない場合は、0 が使用されます。 負のオフセットは、文字列の末尾からのオフセットと解釈されます。

encoding

encoding パラメータには文字エンコーディングを指定します。省略した場合、もしくは null の場合は、 内部文字エンコーディングを使用します。

戻り値

文字列 haystack の中で needle が最初に現れる位置を数字で返します。 needle が見付からなかった場合、false を返します。

変更履歴

バージョン 説明
8.0.0 needle は、空の文字列も受け入れるようになりました。
8.0.0 encoding は、nullable になりました。
7.1.0 負の offset をサポートするようになりました。

参考

  • mb_internal_encoding() - 内部文字エンコーディングを設定あるいは取得する
  • strpos() - 文字列内の部分文字列が最初に現れる場所を見つける

add a note add a note

User Contributed Notes 3 notes

up
3
stestagg at talk21 dot com
17 years ago
It appears that the $offset value is a character count not a byte count.  (This may seem obvious but it isn't explicitly stated)
up
-3
stestagg at talk21 dot com
17 years ago
a sample mb_str_replace function:

function mb_str_replace($haystack, $search,$replace, $offset=0,$encoding='auto'){
    $len_sch=mb_strlen($search,$encoding);
    $len_rep=mb_strlen($replace,$encoding);
   
    while (($offset=mb_strpos($haystack,$search,$offset,$encoding))!==false){
        $haystack=mb_substr($haystack,0,$offset,$encoding)
            .$replace
            .mb_substr($haystack,$offset+$len_sch,1000,$encoding);
        $offset=$offset+$len_rep;
        if ($offset>mb_strlen($haystack,$encoding))break;
    }
    return $haystack;
}
up
-19
stestagg at talk21 dot com
17 years ago
sorry, my previous post had an error.  replace the 1000 with strlen($haystack) to handle strings longer than 1000 chars.

btw. This is an issue with the mbstring functions.  you can't specify the $encoding without specifying a $length, thus this reduces the functionality of mb_substr compared to substr
To Top