[英]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.