简体   繁体   English

替换字符串中的值

[英]Replacing values in string

I have a string which contains certain number of #{number} structures.我有一个字符串,其中包含一定数量的 #{number} 结构。 For example:例如:

#328_#918_#1358 #328_#918_#1358
SKU:#666:#456货号:#666:#456
TEST--#888/#982测试--#888/#982

For each #{number} structure, I have to replace it with a known string.对于每个 #{number} 结构,我必须用已知字符串替换它。

For the first example:对于第一个示例:
#328_#918_#1358 #328_#918_#1358
I have the following strings:我有以下字符串:

328="foo" 328 =“富”
918="bar" 918="酒吧"
1358"arg"第1358章

And the result should be:结果应该是:
foo_bar_arg foo_bar_arg

How do I achieve such effect?我怎样才能达到这样的效果? My current code looks like that:我当前的代码如下所示:

$matches = array();
$replacements = array();
// starting string
$string = "#328_#918:#1358";
// getting all the numbers from the string
preg_match_all("/\#[0-9]+/", $string, $matches);
// getting rid of #
foreach ($matches[0] as $key => &$feature) {
    $feature = preg_replace("/#/", "", $feature);
} // end foreach
// obtaining the replacement values
foreach ($matches[0] as $key => $value) {
    $replacement[$value] = "fizz"; // here the value required for replacement is obtained
} // end foreach

But I have no idea how to actually perform a replacement in $string variable using values from $replacement table.但我不知道如何使用 $replacement 表中的值在 $string 变量中实际执行替换。 Any help is much appreciated!任何帮助深表感谢!

You can use a preg_replace_callback solution:您可以使用preg_replace_callback解决方案:

$string = '#328_#918:#1358
SKU:#666:#456
TEST--#888/#982';
$replacements = [328=>"foo", 918=>"bar", 1358=>"arg"];
echo preg_replace_callback("/#([0-9]+)/", function ($m) use ($replacements) {
    return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
}
,$string);

See the PHP demo .请参阅PHP 演示

The #([0-9]+) regex will match all non-overlapping occurrences of # and one or more digits right after capturing them into Group 1. If there is an item in the replacements associative array with the numeric key, the whole match is replaced with the corresponding value. #([0-9]+)正则表达式将匹配所有不重叠的#和一个或多个数字,然后将它们捕获到第 1 组中。如果replacements关联数组中有一个带有数字键的项目,则整个match 被替换为相应的值。 Else, the match is returned so that no replacement could occur and the match does not get removed.否则,将返回匹配项,这样就不会发生替换并且匹配项不会被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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