php - 从字符串中的数组键替换匹配的字符串
问题描述
我的目标是在一个字符串中找到一个假定数组的键,并在该字符串中用数组中的匹配键替换这些键。
我有一个小而有用的函数,可以在 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!
我怎样才能做到这一点?
解决方案
您可以使用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
) 被传递给函数。
在数组的第一个元素上有第一个捕获组,我们用它来进行替换。
推荐阅读
- node.js - 如何将 ClojureScript 节点 REPL 连接到我的 :node-library shadow-cljs 项目?
- haskell - 使用存在类型 Haskell 时出现类型错误
- cvs2git - cvs2git 在 miration 期间丢失了一些提交
- mysql - Google Cloud Platform - 在一个项目中使用 mysql 实例到另一个项目 - 将一个项目中的 mysql 实例连接到另一个项目
- regex - 使用正则表达式验证掩码和限制货币范围
- php - 在 Shortcode 中更改产品类别的 WooCommerce 添加到购物车消息
- reactjs - 如何检查用户是否在反应中使用firebase进行了身份验证
- tfs - 部署前备份 TFS 版本
- amazon-web-services - 在 AWS EMR 上运行时触发作业挂起
- python - 如何删除多数据库中的 django 模型用户?