[英]PHP replace all instances with single regex pattern
我有一個正則表達式,我想以最有效的方式替換匹配數組中的每個匹配與相應的替換數組。
例如,我有:
$string = '~~hello~~ there, how ~~are~~ ~~you~~?';
$pattern = '/~~(.*?)~~/';
$replacements = array();
$replacements[0] = 'hi';
$replacements[1] = 'am';
$replacements[2] = 'i';
我想把$string
變為:
hi there, how am i?
最初我希望它像下面這樣簡單:
$string = preg_replace($pattern, $replacements, $string);
但它似乎沒有用。 所以第一個問題是:如果$replacements
是一個數組,那么$string
也必須是一個數組嗎?
現在,我可以提出(看似)效率低下的方法,例如計算匹配數並使數組填充適當數量的相同正則數。 但這引出了我們的問題二:是否有更有效的方法? 你會怎么做,PHP專業人士?
你可以在這里使用一個簡單的評估技巧:
print preg_replace('/~~(\w+)~~/e', 'array_shift($replacements)', $st);
array_shift
將簡單地從替換數組中獲取第一個條目。
更好的是使用地圖( "hello" => "hi"
)。
我可能會使用preg_replace_callback
:
$string = '~~hello~~ there, how ~~are~~ ~~you~~?';
$pattern = '/~~(.*?)~~/';
var_dump(preg_replace_callback($pattern,
function($matches) {
static $replacements = array('hi', 'am', 'i'), $i = 0;
return $replacements[$i++ % count($replacements)];
},
$string));
輸出:
string(19) "hi there, how am i?"
如果您要做的就是用另一組特定短語切換這三個特定短語,那么您可以使用str_replace
因為它比preg_replace
快得多。
$subject = "~~hello~~ there, how ~~are~~ ~~you~~?";
$matches = array('~~hello~~', '~~are~~', '~~you~~');
$replace = array('hi', 'am', 'i');
str_replace($matches, $replace, $subject);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.