首页 > 解决方案 > 从字符串中的数组键替换匹配的字符串

问题描述

我的目标是在一个字符串中找到一个假定数组的键,并在该字符串中用数组中的匹配键替换这些键。

我有一个小而有用的函数,可以在 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!

我怎样才能做到这一点?

标签: phpregexpreg-replacepreg-match

解决方案


您可以使用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) 被传递给函数。

在数组的第一个元素上有第一个捕获组,我们用它来进行替换。


推荐阅读