php - 如何使用 preg_replace 用数组中的字符串替换子字符串? (PHP)

标签 php arrays string preg-replace

我有一个包含这些值的数据数组:

Array
(
    [id] => 1
    [myid] => 9
    [date] => 2014-01-30
    [user] => 17
    [reason] => some text here...
)

这个字符串包含引用数据数组索引的数字:

$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"';

是否可以更改括号中的数字,包括将括号中的数字更改为数组中的适当值?

我知道如何使用 (string) preg_replace( (array) $patterns, (array) $replacements, (string) $subject) 但完全不知道如何解决这个问题.

理想情况下,结果字符串可能如下所示:

'1' as "id",'9'  as "myid",'2014-01-30'  as "date",'17'  as "user",'some text here...'  as "reason"

最佳答案

使用preg_replace_callbackstr_replace函数的解决方案:

$columns = '(0) as "id",(1) as "myid",(2) as "date",(3) as "user",(4) as "reason"';

// $arr is your initial array
$result = preg_replace_callback(
                "/(\(\d\)) as \"(\w+?)\",?/i",
                function ($maches) use($arr){
                     return str_replace([$maches[1]], "'". $arr[$maches[2]]. "'", $maches[0]);
                },
                $columns);

print_r($result);

输出:

'1' as "id",'9' as "myid",'2014-01-30' as "date",'17' as "user",'some text here...' as "reason"

关于php - 如何使用 preg_replace 用数组中的字符串替换子字符串? (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37249718/

相关文章:

php - 如果字段不存在则跳过表的 mysql 语句

javascript - 更改数组中每个项目的属性?

c++ - 在函数中引用自动数组迭代器

java - 根据奇怪的协议(protocol)将整数放入字节数组

C++ - 尝试使用字符串函数来反转输入字符串

php - 查询在自定义 PDO 数据库类中运行两次

php - LaravelCollective SSH try catch 异常失败

python - 是否有 Python 模块来解析原始字符串中的换行符符号?

php - 如何在 PHP 中获取本地系统时间?

Python如何从字符串中多次出现之间获取变量