ホームページ  >  記事  >  バックエンド開発  >  strpos を使用して文字列の 2 番目の出現を検索する方法

strpos を使用して文字列の 2 番目の出現を検索する方法

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2024-10-18 14:45:30247ブラウズ

How to Find the Second Occurrence of a String Using strpos

strpos を使用した文字列の 2 番目の出現の検索

PHP の strpos 関数は、通常、最初に出現する文字列の位置を見つけるために使用されます。文字列内の部分文字列。ただし、2 番目以降の出現を取得する必要がある場合もあります。

strpos を使用した再帰

部分文字列の 2 番目の出現を検索するには、次のような方法があります。再帰を使用し、strpos の既存の機能を活用します。これは、strpos を繰り返し呼び出し、前回の出現のインデックスを次の検索の開始位置として渡すことで実現できます。

<code class="php"><?php

/**
 * Find the position of the Xth occurrence of a substring in a string
 *
 * @param string $haystack The input haystack string
 * @param string $needle The substring to search for
 * @param int $number The occurrence number to find
 * @return int|bool The index of the Xth occurrence or false if not found
 */
function strposX($haystack, $needle, $number) {
    // Handle the base case (finding the first occurrence)
    if ($number == 1) {
        return strpos($haystack, $needle);
    } 
    // Recursively search for the Nth occurrence (N > 1)
    elseif ($number > 1) {
        $previousOccurrence = strposX($haystack, $needle, $number - 1);
        // If the previous occurrence is found, continue searching from there
        if ($previousOccurrence !== false) {
            return strpos($haystack, $needle, $previousOccurrence + strlen($needle));
        }
    } 
    // If the conditions are not met, return an error or false
    return false;
}

// Example usage
$haystack = 'This is a test string.';
$needle = 'is';
$secondOccurrence = strposX($haystack, $needle, 2);

if ($secondOccurrence !== false) {
    echo 'The second occurrence of "' . $needle . '" is at index ' . $secondOccurrence . ' in "' . $haystack . '".';
} else {
    echo 'The second occurrence of "' . $needle . '" was not found.';
}</code>

このアプローチでは、再帰を利用して、目的の出現が見つかるまで、部分文字列の後続の出現を繰り返し検索します。が見つかるか、文字列の終わりに達します。

以上がstrpos を使用して文字列の 2 番目の出現を検索する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。