PHP로 다른 문자열에서 부분 문자열의 첫 번째 인스턴스를 삭제하려면 어떻게합니까? 감사.PHP로 문자열의 첫 번째 인스턴스를 삭제하십시오.
$search = "boo";
$str = "testtestbootest";
$pos = strpos(strrev($str), strrev($search));
$newstr = substr($str, 0, $pos) . substr($str, $pos + strlen($search));
PHP로 다른 문자열에서 부분 문자열의 첫 번째 인스턴스를 삭제하려면 어떻게합니까? 감사.PHP로 문자열의 첫 번째 인스턴스를 삭제하십시오.
$search = "boo";
$str = "testtestbootest";
$pos = strpos(strrev($str), strrev($search));
$newstr = substr($str, 0, $pos) . substr($str, $pos + strlen($search));
뭔가 :
당신의 정규식 능력 한계로, 사용 preg_replace이다 그것까지있는 경우 = 1
mixed preg_replace (mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]])
이의 일반적인 생각과 뭔가를 시도 이 같은 트릭을 할 수 있습니다.
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."
죄송합니다. 모든 수정 작업에 이상한 서식 문제가 있습니다.
이것은 복제본입니다. http://stackoverflow.com/questions/3145290/remove-first-and-last-instance-of-a-string 해결책이 제공됩니다. – jordanstephens