>  기사  >  백엔드 개발  >  PHP 배열 일대일 대체 구현 코드

PHP 배열 일대일 대체 구현 코드

高洛峰
高洛峰원래의
2016-12-01 10:28:16926검색

코드 복사 코드는 다음과 같습니다.
header("Content-type: text/html; charset=utf-8")
function multiple_replace_words($word,$ replacement,$ string,$tmp_match='#a_a#'){
preg_match_all('/'.$word.'/',$string,$matches); //모든 키워드 일치
$search = 폭발 (' ,','/'.implode('/,/',$matches[0]).'/')
//일치하는 키워드가 없습니다
if(empty($matches[0 ]) ) return false;
//특별 교체 설정
$count = count($matches[0])
foreach($replace as $key=>$val){
if (! isset($matches[0][$key])) unset($replace[$key]); //범위를 벗어난 대체 제거
}
//특수 대체 배열과 일치하는 배열 병합
for($ i=0;$i<$count;$i++){
$matches[0][$i] = isset($replace[$i])? $replace[$i]: $matches[0][ $i];
}
$replace = $matches[0];
//대체 루프를 방지합니다. 즉, 현재 대체 문자는 여전히 대체 문자입니다. , 임시로 특정 문자로 대체됩니다. $tmp_match
$replace = implode(',',$replace)
$replace = str_replace($word,$tmp_match,$replace); 문자
$replace =explore(', ',$replace);
//대체 처리
$string = preg_replace($search,$replace,$string,1) //한 요소만 교체 한 번에 배열에서
$string = str_replace ($tmp_match,$word,$string); //임시로 대체된 일치 문자를 복원합니다.
return $string>//예제 1
$string = 'aaabaaacaaadaaa';
$word = 'aaa';
$replace = array(null,'xxx','yyy')
echo '원본 텍스트: '.$ string.'
출력: '.multiple_replace_words ($word,$replace,$string).'

'
//예 2
$string = '中文aaab中文ccaaad中文ee';
$word = '중국어';
$replace = array(null,'(중국어 2 대체)','(중국어 3 대체)') 🎜>echo '원본 텍스트:'.$string.'< br/>출력: '.multiple_replace_words($word,$replace,$string)
/*
출력 결과:
원본 텍스트: aaabaaacaaadaaa
출력: aaabxxxcyyydaaa
원본 텍스트: 중국어 aaab 중국어 ccaaad 중국어 eee
출력: 중국어 aaab(중국어 2 대체) ccaaad(중국어 3 대체) eee
//*/

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.