我的目标是在一个字符串中找到一个假定的数组的键,然后在该字符串中,用数组中匹配的键替换这些键。
我有一个有用的小函数,它可以在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!
我该如何实现?
希望这可以解决您对问题的回答!
$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;
[这个问题比正则表达式更容易用strtr
解决。我们可以使用strtr
在array_map
的键周围添加array_map
和$start
值,然后使用$end
进行替换:
$replacements
输出:
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);