如何使用 strpos 尋找字串的第二次出現

Mary-Kate Olsen
發布: 2024-10-18 14:45:30
原創
247 人瀏覽過

How to Find the Second Occurrence of a String Using strpos

使用strpos 尋找字串的第二次出現

PHP 中的strpos 函數通常用於尋找字串第一次出現的位置字串中的子字串。但是,在某些情況下,您可能需要檢索第二次或後續出現的情況。

使用 strpos 遞歸

要找出子字串的第二次出現,一種方法是使用遞歸並利用 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 尋找字串的第二次出現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!