2014-03-04 3 views
1

preg_replace_callback()을 사용하여 문자열에 매개 변수가 포함 된 함수를 호출하려고합니다.문자열에 매개 변수가있는 함수 이름 preg_replace_callback

$string = "some text ucfirst('asd')"; 
$pattern = "~ucfirst([a-z]+)\(\)~"; 
$string = preg_replace_callback($pattern, "ucasef", $string); 

echo $string; // some text Asd 

패턴에 대한 도움이 필요하며 예제 출력을 수행하는 데 사용하는 방법도 필요합니다.

이 당신이 그것을 사용할 수있는 방법입니다

답변

1

, 나는 코드를 명확히하기 위해 몇 가지 의견을 추가했습니다 :

$input = "some text ucfirst('name') and strtoupper (\"shout\" ). Maybe also make it strtolower( 'LOWER') or do('nothing')."; 

$pattern = '~ 
(\w+)  # Match the function name and put it in group 1 
\s*\(\s* # Some optional whitespaces around (
("|\')  # Match either a double or single quote and put it in group 2 
(.*?)  # Match anything, ungreedy until ... 
\2   # Match what was matched in group 2 
\s*\)  # Some optional whitespaces before) 
~xs';  # XS modifiers, x to make this fancy formatting/commenting and s to match newlines with the dot "." 

$output = preg_replace_callback($pattern, function($v){ 
    $allowed = array('strtolower', 'strtoupper', 'ucfirst', 'ucwords'); // Allowed functions 
    if(in_array(strtolower($v[1]), $allowed)){ // Check if the function used is allowed 
     return call_user_func($v[1], $v[3]); // Use it 
    }else{ 
     return $v[0]; // return the original value, you might use something else 
    } 
}, $input); 

echo $output; 

출력 : 텍스트 이름과 SHOUT을. 어쩌면 그것을 낮추거나 할 수도 있습니다 ('아무것도').

+0

아름다운 답변. Thankyou –

+0

한 단계 더 나아가려면 실제로 두 단계! .. 1) 위의 코드를 편집하여 여러 인수를 취하는'str_replace'와 같은 함수를 처리하고 싶습니다. 2) 그리고 최종 해결책은 'ucfirst (str_replace ('_ ',' ', test_test'))와 같은 함수 내에서 함수를 처리 할 것입니다. 감사합니다. –

+0

@StewartMegaw 제가 당신에게 뭔가를 말해야한다고 생각합니다 : ** 1) ** 당신은 [camelion] (http://meta.stackexchange.com/questions/43478)처럼 행동합니다. 대답을 몇 번이고 또 다시 편집하는 것은 고통입니다 ** 2) ** 당신은 정말로 뭔가를 시도하고 약간의 노력을 보여 주어야합니다. 이것은 무료 코딩 서비스가 아닙니다 ** 3) ** 당신이 시도한 것을 가지고 새로운 질문을 게시 할 때 당신이 원하는 것을 구현하려고합니다 ** 4) ** 당신이 어떻게 왔는지 모르겠습니다. 새로운 요구 사항과 함께하지만 구현하는 데는 어려움이 있습니다. 재귀 적 솔루션이 필요하고 강력한 파서를 만들 수 있습니다. – HamZa

관련 문제