2012-07-30 69 views
-3

我需要PHP中的功能來處理替換這樣的事情。PHP替換路線系統

$pattern = ':foo/anotherString'; 

$replacement = array(
    'foo' => 'HelloMe' 
); 

bazFunction($pattern, $replacement); // return 'HelloMe/anotherString'; 

此方法在某些框架中用作路由模式。我想知道哪個函數處理。

+0

沒用或不清楚? – sweb 2012-07-30 09:13:56

回答

1

本應該做的(5.3,因爲封閉的需要)

function my_replace($pattern, $replacement) { 
    // add ':' prefix to every key 
    $keys = array_map(function($element) { 
    return ':' . $element; 
    }, array_keys($replacement)); 

    return str_replace($keys, array_values($replacement), $pattern); 
} 

如果直接傳遞東西你不會需要這個功能210

str_replace(array(':foo'), array('HelloMe'), ':foo/anotherString'); 
1
$string = "foo/anotherString"; 
$replacement = array('foo','HelloMe'); 
$newString = str_replace($replacement[],,$string); 
+0

你錯過了'$ string'中的':' – ManseUK 2012-07-30 09:19:25

0

看來,PHP得到了你的功能...

str_replace (":foo", "HelloMe" , $pattern) 

會給你這樣的輸出:HelloMe/anotherString