source

문자열에서 마지막으로 발생한 문자열 바꾸기

goodcode 2022. 10. 6. 21:39
반응형

문자열에서 마지막으로 발생한 문자열 바꾸기

마지막으로 나온 문자열을 문자열의 다른 문자열로 대체할 수 있는 매우 빠른 방법을 아는 사람 있나요?

문자열의 마지막 문자는 문자열의 마지막 문자가 아닐있습니다.

예제:

$search = 'The';
$replace = 'A';
$subject = 'The Quick Brown Fox Jumps Over The Lazy Dog';

예상 출력:

The Quick Brown Fox Jumps Over A Lazy Dog

다음 기능을 사용할 수 있습니다.

function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos !== false)
    {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }

    return $subject;
}

다른 1-라이너(예비 없음):

$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';

echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm

다음 다소 콤팩트한 솔루션에서는 PCRE 포지티브룩어헤드 어설션을 사용하여 대상 서브스트링의 마지막 오카렌스, 즉 동일한 서브스트링의 다른 오카렌스 뒤에 없는 서브스트링의 오카렌스와 일치시킵니다.따라서 이 예에서는,last 'fox''dog'.

$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);

출력:

The quick brown fox, fox, fox jumps over the lazy dog!!!

다음과 같이 할 수 있습니다.

$str = 'Hello world';
$str = rtrim($str, 'world') . 'John';

결과는 'Hello John'입니다.

이것은 오래된 질문입니다만, 왜 모두가 가장 심플한 regexp 베이스의 솔루션을 간과하고 있는 것일까요. , regexp」를 붙이면 .*에서.을 사용하다

$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);

이렇게 하면 "fox"의 마지막 인스턴스가 "DUCK"로 대체되어 다음과 같이 인쇄됩니다.

The quick brown fox, fox, fox, DUCK, jumps over etc.

이것도 동작합니다.

function str_lreplace($search, $replace, $subject)
{
    return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}

업데이트 조금 더 간결한 버전(http://ideone.com/B8i4o):

function str_lreplace($search, $replace, $subject)
{
    return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
$string = "picture_0007_value";
$findChar =strrpos($string,"_");
if($findChar !== FALSE) {
  $string[$findChar]=".";
}

echo $string;

코드의 실수를 제외하면 파루크 우날은 최고의 앤서를 가지고 있다.한 가지 기능이 효과가 있습니다.

strpos()를 사용하여 마지막 일치를 찾을 수 있습니다.

$string = "picture_0007_value";
$findChar =strrpos($string,"_");

$string[$findChar]=".";

echo $string;

출력: picture_0007.value

수락된 답변의 약자

function str_lreplace($search, $replace, $subject){ 
    return is_numeric($pos=strrpos($subject,$search))?
    substr_replace($subject,$replace,$pos,strlen($search)):$subject;
}

짧은 버전:

$NewString = substr_replace($String,$Replacement,strrpos($String,$Replace),strlen($Replace));

regex를 사용하는 것은 일반적으로 비regex 기술에 비해 성능이 떨어지지만, regex가 제공하는 제어력과 유연성은 높이 평가합니다.

스니펫에서는 를 구분하지 않도록 합니다(대문자와 소문자를구분하지 않음).\i, 은 이 단어 경계(「」, 「」, 「」)가 포함됩니다.\b(비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유, 비유.

또, I'm supper를 사용하여\Kmetacharacter를 사용하여 캡처 그룹/백레퍼런스가 필요 없도록 전체 문자열 일치를 리셋합니다.

코드: (데모)

$search = 'The';
$replace = 'A';
$subject = "The Quick Brown Fox Jumps Over The Lazy Dog's Thermos!";

echo preg_replace(
         '/.*\K\b' . preg_quote($search, '/') . '\b/i',
         $replace,
         $subject
     );

출력:

  The Quick Brown Fox Jumps Over A Lazy Dog's Thermos!
# ^^^                            ^            ^^^
# not replaced                replaced        not replaced

단어 경계 없음: (데모)

echo preg_replace(
         '/.*\K' . preg_quote($search, '/') . '/i',
         $replace,
         $subject
     );

출력:

  The Quick Brown Fox Jumps Over The Lazy Dog's Armos!
# ^^^                            ^^^            ^
# not replaced              not replaced        replaced

아래 수정한 잭의 코드(https://stackoverflow.com/a/11144999/9996503)).규칙적인 표현에 주의하세요!다음 사항을 고려하십시오.

$string = 'Round brackets (parentheses) "()", square brackets "()"';
$find = '()';
$replace = '[]';
// Zack's code:
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
var_dump($result); // Output: NULL
// Correct code:
$result = strrev(preg_replace('/'.preg_quote(strrev($find)).'/', strrev($replace), strrev($string), 1));
echo $result; //Output: Round brackets (parentheses) "()", square brackets "[]"

문자열 끝과 일치하려면 레지스트리 식에 "$"를 사용합니다.

$string = 'The quick brown fox jumps over the lazy fox';
echo preg_replace('/fox$/', 'dog', $string);

//output
'The quick brown fox jumps over the lazy dog'

관심있는 고객:regex를 사용하여 오른쪽에서 치환할 수 있도록 preg_match를 사용하는 함수를 작성했습니다.

function preg_rreplace($search, $replace, $subject) {
    preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
    $lastMatch = end($matches);

    if ($lastMatch && false !== $pos = strrpos($subject, $lastMatchedStr = $lastMatch[0])) {
        $subject = substr_replace($subject, $replace, $pos, strlen($lastMatchedStr));
    }

    return $subject;
}

또는 두 옵션의 간략한 조합/실장:

function str_rreplace($search, $replace, $subject) {
    return (false !== $pos = strrpos($subject, $search)) ?
        substr_replace($subject, $replace, $pos, strlen($search)) : $subject;
}
function preg_rreplace($search, $replace, $subject) {
    preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
    return ($lastMatch = end($matches)) ? str_rreplace($lastMatch[0], $replace, $subject) : $subject;
}

https://stackoverflow.com/a/3835653/3017716 및 https://stackoverflow.com/a/23343396/3017716를 기반으로 합니다.

언급URL : https://stackoverflow.com/questions/3835636/replace-last-occurrence-of-a-string-in-a-string

반응형