2012-04-28 2 views
1

다음 코드가 있습니다.preg_replace - 배열의 임의의 단어

<?php 
$user['username'] = 'Bastian'; 

$template = 'Hello {user:username}'; 
$template = preg_replace('/\{user\:([a-zA-Z0-9]+)\}/', $user['\1'], $template); 
echo $template; 

// Output: 
// Notice: Undefined index: \1 in C:\xampp\htdocs\test.php on line 5 
// Hello 

나는 당신이 내가 무엇을 할 것인지를 안다. $ user [ '$ 1'], $ user [ "$ 1"] 또는 $ user [$ 1]을 (를) 대체하려고합니다. 아무것도 작동하지 않습니다!

도와 주시면 감사하겠습니다. =) 미리 감사드립니다!

답변

2

preg_replace_callback() - preg_replace()의 대체 코드는 문자열이므로 PHP 코드를 사용할 수 없습니다. 그리고 no, /e 수식어는 eval이 악이기 때문에 해결책이 아닙니다.

여기 예입니다 (이것은 PHP 5.3이 필요하지만 당신은 어쨌든 최신 버전을 사용한다!) : 당신이 오래된 PHP 버전을 사용하는이 경우

$user['username'] = 'FooBar'; 
$template = 'Hello {user:username}'; 
echo preg_replace_callback('/\{user\:([a-zA-Z0-9]+)\}/', function($m) use ($user) { 
    return $user[$m[1]]; 
}, $template); 

, 당신은 이런 식으로 할 수 있습니다. 이 때문에 비록 전역 변수의 사용에 훨씬 못 생겼어의 :

function replace_user($m) { 
    global $user; 
    return $user[$m[1]]; 
} 
echo preg_replace_callback('/\{user\:([a-zA-Z0-9]+)\}/', 'replace_user', $template); 

그러나 자신에 그것을 구현하는 대신 템플릿 엔진 같은 h2o을 사용하는 것이 좋습니다.

+0

고마워요 ^^ {user:username}'; echo preg_replace_callback ('/ \ {사용자 \ : ([a-zA-Z0-9] +) \} /', 'repl', $ template); // 출력 : // 안녕하세요 FooBar Patrick