【问题标题】:Get matches from a preg_replace and use them as an array key从 preg_replace 获取匹配项并将它们用作数组键
【发布时间】:2019-05-18 00:43:35
【问题描述】:

我想从字符串中获取匹配项,并在数组中使用它们作为键,将字符串中的值更改为数组的值。

如果它更容易实现,我可以将幻想标签从 %!也适用于 JS/jQuery 中没有问题的任何东西。此脚本用于外部 JS 文件并更改一些我无法从 JS/jQuery 访问的变量。所以我想用 PHP 插入它们并将它们缩小并压缩到浏览器。

$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';

$string = preg_replace('%!(.*?)!%',$array[$1],$string);
echo $string;

【问题讨论】:

  • 改用preg_match_all
  • 对不起 :D 是的,当然。但我的主要问题是,如何取出标签之间的字符串并将其用作现有数组中的键以将数组值放入字符串中

标签: php arrays string preg-replace


【解决方案1】:

您可以使用array_mappreg_quote 将数组的键转换为正则表达式,然后将数组的值用作preg_replace 数组形式的替换字符串:

$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';
$regexes = array_map(function ($k) { return "/" . preg_quote("%!$k!%") . "/"; }, array_keys($array));
$string = preg_replace($regexes, $array, $string);
echo $string;

输出:

This is just a Test String and i wanna Change the Variable

Demo on 3v4l.org

【讨论】:

  • 太棒了!非常感谢:)
  • @Rico 不用担心。我很高兴能帮上忙。
猜你喜欢
  • 2012-08-21
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多