【发布时间】:2020-01-22 04:29:33
【问题描述】:
我的目标是,在一个字符串中,找到一个假定数组的键,并在该字符串中,用数组中匹配的键替换这些键。
我有一个小而有用的函数,可以在 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!
我怎样才能做到这一点?
【问题讨论】:
标签: php regex preg-replace preg-match