2012-05-17 26 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,我認爲它做什麼要求。任何理由請...幫助我找出問題。 –