简体   繁体   English

从字符串中的数组键替换匹配的字符串

[英]Replacing matching strings from array keys in a string

My goal here is to, within a string, find a supposed array's keys and in that string, replace these keys with the matching keys from the array.我的目标是在一个字符串中找到一个假设数组的键,并在该字符串中用数组中的匹配键替换这些键。

I have a small, useful function that finds all my strings between 2 delimiters (sandbox link: https://repl.it/repls/UnlinedDodgerblueAbstractions ):我有一个小而有用的函数,它可以在 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];
}

Example:例子:

findBetween( 'This thing should output _$this_key$_ and also _$this_one$_ so that I can match it with an array!', '_$', '$_')

Should return an array with the values ['this_key', 'this_one'] as it does.应该像它一样返回一个值为['this_key', 'this_one']的数组。 Question is, how can I take these and replace them with an associative array's values?问题是,我怎样才能将这些替换为关联数组的值?

Assume my array is this:假设我的数组是这样的:

[
    'this_key' => 'love',
    'this_one' => 'more love'
];

My output should be this:我的输出应该是这样的:

This thing should output love and also more love so that I can match it with an array!

How can I achieve this?我怎样才能做到这一点?

This is a problem that might be more readily solved with strtr than regex.这是一个问题,使用strtr可能比使用正则表达式更容易解决。 We can use array_map to add the $start and $end values around the keys of $replacements , and then use strtr to do the substitution:我们可以使用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);

Output:输出:

This thing should output love and also more love so that I can match it with an array!

Demo on 3v4l.org 3v4l.org 上的演示

If performance is an issue because you have to regenerate the $replacements array each time, this loop is much faster:如果由于每次都必须重新生成$replacements数组而导致性能问题,则此循环要快得多:

foreach ($replacements as $key => $value) {
    $new_reps["_\$$key\$_"] = $value;
}

Performance comparison demo on 3v4l.org 3v4l.org 上的性能比较演示

You may use preg_replace_callback :您可以使用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;

You have a demo here .在这里有一个演示。

The regular expression, explained:正则表达式,解释:

_              # 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 '_'

For every match, the matching data ( $mathces ) is passed to the function.对于每个匹配项,匹配数据 ( $mathces ) 将传递给函数。

On the first element of the array there is the first capturing group, that we use to do the replacement.在数组的第一个元素上有第一个捕获组,我们用它来进行替换。

Hope this resolves your answer to the question !希望这能解决您对问题的回答!

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM