2012-05-17 30 views
1
$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); 
     } 
} 

当我回声$内容输出:如何在php中替换字符串的位置?

ABC def ghi ABC def ghi ABC def ghi ABC

但我想结果是 “ABC def ghi abc def ghi ABC def ghi abc” 因为$n % 2 == 0,如何解决?

+0

'$ n'在循环中没有变化,所以它总是偶数或总是奇数。 – Arjan

+0

使用'preg_match'而不是'preg_match_all' ...目前,它返回找到的所有匹配。 'preg_match'将只返回第一个匹配。 –

回答

0

一种方法是使用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); 
-1

试试这个:

<?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; 
?> 

希望它有帮助。

+0

为什么downvote,我认为它做什么要求。任何理由请...帮助我找出问题。 –