2011-10-06 8 views
0

정규식 바꾸기를 원하지만 찾을 때마다하고 싶지 않습니다. 내가 preg_replace_callback 내가 사용하는 데 필요한 것, 그리고 거기에 내 임의의 체크를 할 생각하지만 콜백 함수를 여러 매개 변수를 전달하는 방법을 알아낼 수 없습니다. 궁극적으로 둘 이상이 필요 하겠지만, 두 가지 일을 할 수 있다면 더 많은 일을 할 수있을 것입니다.여러 매개 변수가있는 PHP preg_replace_callback

예를 들어 나는 시간의 50 %를 대체하고 다른 시간은 찾은 것을 반환하고 싶습니다. 여기에 내가 함께해온 몇 가지 기능이 있지만 그럴 수는 없습니다.

function pick_one($matches, $random) { 
    $choices = explode('|', $matches[1]); 
    return $random . $choices[array_rand($choices)]; 
} 

function doSpin($content) { 

$call = array_map("pick_one", 50); 
    return preg_replace_callback('!\[%(.*?)%\]!', $call, $content); 
/* return preg_replace_callback('!\[%(.*?)%\]!', 'pick_one($1, 50)', $content); */ 
} 

$content = 'This [%should|ought|would|could%] make it much [%more convenient|faster|easier%] and help reduce duplicate content.'; 

echo doSpin($content).'<br/>'; 

감사 알렌은

답변

1

직접 여러 개의 매개 변수를 전달할 수 없습니다. 그러나 할 수있는 일은 함수를 클래스 메서드로 변경 한 다음 함수에 사용할 값 (예 : $random)으로 설정된 멤버 속성이있는 클래스의 인스턴스를 만드는 것입니다.

0
<?php 

function pick_one($groups) { 

// half of the time, return all options 
    if (rand(0,1) == 1) { 
    return $groups[1]; 
    }; 

    // the other half of the time, return one random option 
    $choices = explode('|', $groups[1]); 
    return $choices[array_rand($choices)]; 

} 

function doSpin($content) { 

    return preg_replace_callback('!\[%(.*?)%\]!', 'pick_one', $content); 

} 

$content = 'This [%should|ought|would|could%] make it much [%more convenient|faster|easier%] and help reduce duplicate content.'; 

echo doSpin($content).'<br/>'; 
관련 문제