2016-12-31 55 views
0

我想用數組中的實際值(值爲864和987)替換下面給出的字段,但我不知道如何用[crowdpdf-total=field_585b0b3288d2e]替換爲[crowdpdf-total=field_585b0b3288d2e]例如864[crowdpdf-total=field_585b0b3288d2f]987用正則表達式在php中搜索並替換部分字符串

數組:

array (
'field_585b0b3288d2e'=> 864, 
'field_585b0b3288d2f => 987 
) 

字符串:

etc etc etc content 
[crowdpdf-total=field_585b0b3288d2e] 
etc etc [crowdpdf-total=field_585b0b3288d2f] 
etc content 

我擅長的事情很多,但由於某些原因,我從來沒有完全理解正則表達式完全。 ..我想正則表達式是用實際值替換[crowdpdf-total={nameoffield}]的方式嗎?正則表達式是去這裏的路嗎?

我希望字符串是:

etc etc etc content 
864 
etc etc 987 
etc content 

澄清:
的實際值我知道如何更換,所以我可以做這樣的替代品。 [crowdpdf-total=864],我可以通過刪除[crowdpdf-total=只是用空字符串替換[crowdpdf-total=,但是接下來我會在每個值的末尾添加一個額外的括號。

+1

時間瞭解它完全閱讀這本書[書籍](http://shop.oreilly.com/product/9780596528126.do)。 (不要給我魚,但教我魚!) –

+0

@ Meninx-メネンックス - 這樣的評論並沒有真正增加任何價值,但感謝提示:-) – bestprogrammerintheworld

回答

3

你不需要爲此使用正則表達式。一個簡單的字符串替換就可以了:

<?php 

$string = <<<EOT 
etc etc etc content 
[crowdpdf-total=field_585b0b3288d2e] 
etc etc [crowdpdf-total=field_585b0b3288d2f] 
etc content 
EOT; 

$replacements = [ 
    'field_585b0b3288d2e' => 864, 
    'field_585b0b3288d2f' => 987, 
]; 

foreach ($replacements as $find => $replace) { 
    $string = str_replace("[crowdpdf-total=$find]", $replace, $string); 
} 

echo $string; 

它輸出:

etc etc etc content 
864 
etc etc 987 
etc content 

Test it online,如果你想。

+0

啊。當然!我以爲我正在走錯方向。感謝您指導我走向正確的方向! :-) – bestprogrammerintheworld