$text = "abc def ghi abc def ghi abc def ghi abc"
$search = "abc";
$regex = '/('s)'.$search.'('s)/i';
$array_key = array();
if(preg_match_all($regex, $text, $tmp)) {
$array_key = $tmp[0];
$n = count($tmp[0]);
for($i=0; $i<$n; $i++) {
if($n % 2 == 0) {
$content = str_replace($array_key[$i], 'ABC', $text);
}
}
当我回显$content输出时:
"ABC def ghi ABC def ghi ABC def ghi ABC
">
但是我希望结果是"ABC def ghi abc def ghi ABC def ghi abc
",因为$n % 2 == 0
,如何解决呢?
问题是str_replace替换所有出现的针。
也。。您必须使用正则表达式吗? 你看过这个 http://bluedogwebservices.com/replace-every-other-occurrence-with-str_replace/吗?
一种方法是使用 preg_replace_callback
和全局变量来跟踪迭代。这是下面采取的方法。
$replacer_i = 0;
function replacer( $matches ) {
global $replacer_i;
return $replacer_i++ % 2 === 0
? strtoupper($matches[0])
: $matches[0];
}
$string = "abc def ghi abc def ghi abc def ghi abc";
$string = preg_replace_callback( "/abc/", "replacer", $string );
// ABC def ghi abc def ghi ABC def ghi abc
print $string;
另一种方法是拆分字符串,并将"abc"的所有其他实例替换为其大写形式,然后将各个部分粘合在一起形成一个新字符串:
$string = "abc def ghi abc def ghi abc def ghi abc";
$aparts = explode( " ", $string );
$countr = 0;
foreach ( $aparts as $key => &$value ) {
if ( $value == "abc" && ( $countr++ % 2 == 0 ) ) {
$value = strtoupper( $value );
}
}
// ABC def ghi abc def ghi ABC def ghi abc
print implode( " ", $aparts );
试试这个:
<?php
$text = "abc def ghi abc def ghi abc def ghi abc";
$search = "ghi";
$regex = '/('.$search.')(.*)/i';
$array_key = array();
if(preg_match($regex, $text, $tmp)) {
$c = strtoupper($tmp[1]);
$content = str_replace( $tmp[1] . $tmp[2], $c . $tmp[2], $tmp[0] );
$content = str_replace( $tmp[1] . $tmp[2], $content, $text );
}
echo $content;
?>
希望对您有所帮助。