[英]Replacing matching strings from array keys in a string
我的目標是在一個字符串中找到一個假設數組的鍵,並在該字符串中用數組中的匹配鍵替換這些鍵。
我有一個小而有用的函數,它可以在 2 個分隔符(沙盒鏈接: https : //repl.it/repls/UnlinedDodgerblueAbstractions )之間找到我的所有字符串:
function findBetween( $string, $start, $end )
{
$start = preg_quote( $start, '/' );
$end = preg_quote( $end, '/' );
$format = '/(%s)(.*?)(%s)/';
$pattern = sprintf( $format, $start, $end );
preg_match_all( $pattern, $string, $matches );
$number_of_matches = is_string( $matches[2] ) ? 1 : count( $matches[2] );
if( $number_of_matches === 1 ) {
return $matches[2];
}
if( $number_of_matches < 2 || empty( $matches ) ) {
return False;
}
return $matches[2];
}
例子:
findBetween( 'This thing should output _$this_key$_ and also _$this_one$_ so that I can match it with an array!', '_$', '$_')
應該像它一樣返回一個值為['this_key', 'this_one']
的數組。 問題是,我怎樣才能將這些替換為關聯數組的值?
假設我的數組是這樣的:
[
'this_key' => 'love',
'this_one' => 'more love'
];
我的輸出應該是這樣的:
This thing should output love and also more love so that I can match it with an array!
我怎樣才能做到這一點?
這是一個問題,使用strtr
可能比使用正則表達式更容易解決。 我們可以使用array_map
在$replacements
的鍵周圍添加$start
和$end
值,然后使用strtr
進行替換:
$str = 'This thing should output _$this_key$_ and also _$this_one$_ so that I can match it with an array!';
$replacements = [
'this_key' => 'love',
'this_one' => 'more love'
];
$start = '_$';
$end = '$_';
$replacements = array_combine(array_map(function ($v) use ($start, $end) { return "$start$v$end"; }, array_keys($replacements)), $replacements);
echo strtr($str, $replacements);
輸出:
This thing should output love and also more love so that I can match it with an array!
如果由於每次都必須重新生成$replacements
數組而導致性能問題,則此循環要快得多:
foreach ($replacements as $key => $value) {
$new_reps["_\$$key\$_"] = $value;
}
3v4l.org 上的性能比較演示
您可以使用preg_replace_callback :
<?php
$str = 'This thing should output _$this_key$_ and also _$this_one$_ so that I can match it with an array!';
$replacements = [
'this_key' => 'love',
'this_one' => 'more love'
];
$replaced = preg_replace_callback('/_\$([^$]+)\$_/', function($matches) use ($replacements) {
return $replacements[$matches[1]];
}, $str);
print $replaced;
你在這里有一個演示。
正則表達式,解釋:
_ # Literal '_'
\$ # Literal '$' ($ needs to be scaped as it means end of line/string)
( # Begin of first capturing group
[^$]+ # One carcter that cannot be "$", repeated 1 or more times
) # End of first capturing group
\$ # Literal '$'
_ # Literal '_'
對於每個匹配項,匹配數據 ( $mathces
) 將傳遞給函數。
在數組的第一個元素上有第一個捕獲組,我們用它來進行替換。
希望這能解決您對問題的回答!
$items['this_key'] = 'love';
$items['this_one'] = 'more love';
$string = 'This thing should output _$this_key$_ and also _$this_one$_ so that I can match it with an array!';
$this_key = $items['this_key'];
$this_one = $items['this_one'];
$string = str_replace('_$this_key$_',$this_key,$string);
$string = str_replace('_$this_one$_',$this_one,$string);
echo $string;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.