2010-07-12 4 views
1

PHP로 다른 문자열에서 부분 문자열의 첫 번째 인스턴스를 삭제하려면 어떻게합니까? 감사.PHP로 문자열의 첫 번째 인스턴스를 삭제하십시오.

$search = "boo"; 
$str = "testtestbootest"; 
$pos = strpos(strrev($str), strrev($search)); 
$newstr = substr($str, 0, $pos) . substr($str, $pos + strlen($search)); 
+0

이것은 복제본입니다. http://stackoverflow.com/questions/3145290/remove-first-and-last-instance-of-a-string 해결책이 제공됩니다. – jordanstephens

답변

3

뭔가 :

1

이의 일반적인 생각과 뭔가를 시도 이 같은 트릭을 할 수 있습니다.

function replaceFirst($input, $search, $replacement){ 
    $pos = stripos($input, $search); 
    if($pos === false){ 
     return $input; 
    } 
    else{ 
     $result = substr_replace($input, $replacement, $pos, strlen($search)); 
     return $result; 
    } 
} 

$input = "This is a test. This is only a test."; 
$search = "test"; 
echo replaceFirst($input, $search, "replaced!"); 
// "This is a replaced!. This is only a test." 

죄송합니다. 모든 수정 작업에 이상한 서식 문제가 있습니다.

관련 문제