![](/img/trans.png)
[英]PHP implement preg_match with an array then preg_replace the matches
[英]Get matches from a preg_replace and use them as an array key
我想從字符串中獲取匹配項,並在數組中將它們用作鍵,以將字符串中的值更改為數組的值。
如果更容易實現,我可以從%更改Fantasy標簽! 還可以解決JS / jQuery中沒有問題的任何問題。 該腳本用於外部JS文件並更改一些變量,這些變量我無法從JS / jQuery訪問。 所以我想用PHP插入它們,然后將它們縮小並發送到瀏覽器。
$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';
$string = preg_replace('%!(.*?)!%',$array[$1],$string);
echo $string;
您可以將array_map
與preg_quote
一起使用,以將數組的鍵轉換為正則表達式,然后將數組的值用作preg_replace
數組形式的替換字符串:
$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';
$regexes = array_map(function ($k) { return "/" . preg_quote("%!$k!%") . "/"; }, array_keys($array));
$string = preg_replace($regexes, $array, $string);
echo $string;
輸出:
This is just a Test String and i wanna Change the Variable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.