<?php
header(
"Content-type: text/html; charset=utf-8"
);
function
multiple_replace_words(
$word
,
$replace
,
$string
,
$tmp_match
='#a_a#'){
preg_match_all('/'.
$word
.'/',
$string
,
$matches
);
$search
=
explode
(',','/'.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];
$replace
= implode(',',
$replace
);
$replace
=
str_replace
(
$word
,
$tmp_match
,
$replace
);
$replace
=
explode
(',',
$replace
);
$string
= preg_replace(
$search
,
$replace
,
$string
,1);
$string
=
str_replace
(
$tmp_match
,
$word
,
$string
);
return
$string
;
}
$string
= 'aaabaaacaaadaaa';
$word
= 'aaa';
$replace
=
array
(null,'xxx','yyy');
echo
'原文:'.
$string
.'<br/>输出:'.multiple_replace_words(
$word
,
$replace
,
$string
).'<br/><br/>';
$string
= '中文aaab中文ccaaad中文eee';
$word
= '中文';
$replace
=
array
(null,'(替换中文2)','(替换中文3)');
echo
'原文:'.
$string
.'<br/>输出:'.multiple_replace_words(
$word
,
$replace
,
$string
);