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 학습자의 빠른 성장을 도와주세요!