PHP 문자열에서 마지막으로 나타난 문자열을 대체 하시겠습니까? 바꾸는 매우 빠른 방법을 알고

누구든지 마지막 문자열을 문자열의 다른 문자열로 바꾸는 매우 빠른 방법을 알고 있습니까?



답변

이 기능을 사용할 수 있습니다 :

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

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

    return $subject;
}

답변

preg이없는 또 다른 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 긍정 lookahead 어설 션 을 사용하여 관심있는 부분 문자열의 마지막 항목, 즉 동일한 부분 문자열의 다른 항목이 뒤 따르지 않는 부분 문자열의 항목과 일치시킵니다. 따라서 예는이 대체 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’입니다.

문안 인사


답변

이것은 또한 작동합니다 :

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 = 'The quick brown fox jumps over the lazy dog';
$find_me = 'dog';

preg_replace('/'. $find_me .'$/', '', $string);

끝 $는 문자열의 끝을 나타냅니다.