2013-04-20 1 views
1

특정 패턴을 증분 카운트 된 숫자로 대체해야합니다. 내 코드 :PHP를 사용하여 증분 카운트 된 숫자로 preg_replace하는 방법?

$text = "Hello (apple) hello (banana) hello (cucumber)"; 
$pattern = '/\(([^\)]*)\)/s'; 

$i = 0; 
$returnText = preg_replace_callback($pattern, function($matches) use ($i) { 
    return '<sup>['.$i++.']</sup>'; 
}, $text); 

echo $returnText; 

결과 :

Hello [0] hello [0] hello [0] 

내가 필요한 것은 : 내가 뭘 잘못

Hello [0] hello [1] hello [2] 

?

답변

4

참조로 $ i를 (를) 잊어 버리는 것을 잊었습니다.

$returnText = preg_replace_callback($pattern, function($matches) use (&$i) 
: 그냥 & 전에 $ 내가를 추가