最佳化「替換字串中的佔位符變數」
人們可能會遇到各種場景,其中識別和替換字符字串中的佔位符變數至關重要。此程式碼片段示範了一個動態替換函數dynStr,它可以定位大括號({}) 括起來的鍵值對並相應地更新它們:
function dynStr($str,$vars) { preg_match_all("/\{[A-Z0-9_]+\}+/", $str, $matches); foreach($matches as $match_group) { foreach($match_group as $match) { $match = str_replace("}", "", $match); $match = str_replace("{", "", $match); $match = strtolower($match); $allowed = array_keys($vars); $match_up = strtoupper($match); $str = (in_array($match, $allowed)) ? str_replace("{".$match_up."}", $vars[$match], $str) : str_replace("{".$match_up."}", '', $str); } } return $str; } $variables = array("first_name" => "John","last_name" => "Smith","status" => "won"); $string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.'; echo dynStr($string,$variables); // Would output: 'Dear John Smith, we wanted to tell you that you won the competition.'
但是,正如作者強調的那樣,此實作存在冗餘數組存取並且顯得計算密集。我們可以透過消除正規表示式的使用並根據「vars」數組中的鍵值對實現簡單的字串替換來簡化這一過程:
$variables = array("first_name" => "John","last_name" => "Smith","status" => "won"); $string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.'; foreach($variables as $key => $value){ $string = str_replace('{'.strtoupper($key).'}', $value, $string); } echo $string; // Dear John Smith, we wanted to tell you that you won the competition.
這種方法刪除了不必要的嵌套數組遍歷,並且簡化替換過程,從而產生更乾淨、更有效率的程式碼。
以上是如何有效率地替換字串中的佔位符變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!