gpt4 book ai didi

php - 避免替换替换字符串中找到的占位符

转载 作者:行者123 更新时间:2023-12-04 15:32:56 25 4
gpt4 key购买 nike

假设我有这个字符串:

"my string ? other string ?"
  • 我想替换第一个“?”与“第一个参数?”(注意文本内的占位符?)
  • 和第二个“第二个参数”。

如果我执行 preg_replace 我会得到这个:

my string first param second param other string ?
^^^^^^^^^^^^^^^^^^^^^^^^ ^
WRONG NOT REPLACED

基本上,由于第一个替换也有占位符,因此 preg_replace 很愚蠢地替换了该占位符,而不是最后真正的第二个占位符。

带有preg_replace的代码:

$search = ["?", "?"];
$params = ["first param ?", "second param"];
$query ="first text ? other text ?";

//> Marker in the query are ?, so I create the array to preg_replace
$search = array_fill(0,count($params),'/\?/');
$query = preg_replace(
$search, // a list of ?
$params, // escaped values
$query, // from query
1 // replace only 1 time
);
//output: first text first param second param other text ?

有关如何避免在替换内容中搜索占位符的任何提示吗?

带有preg_replace的实时代码:http://sandbox.onlinephpfunctions.com/code/e705ba454d030103344bc826e0fe0bf42d5b7b90

也不适用于str_replace

$search = ["?", "?"];
$params = ["first param ?", "second param"];
$query ="first text ? other text ?";

$query = str_replace ($search, $params, $query);
echo $query;

// output: first text first param second param other text first param second param

带有 str_replace 的实时代码: http://sandbox.onlinephpfunctions.com/code/dc259325411ee42de759f145eac78b339f329f74

异常输出

给定:

$search = ["?", "?"];
$params = ["first param ?", "second param"];
$query ="first text ? other text ?";

预期输出是:

first text first param ? other text second param
^^^^^^^^^^^^^ ^^^^^^^^^^^^
first placeholder second placeholder

带有 3 个参数的异常输出

$search = ["?", "?", "?"];
$params = ["first param", "second param ?", "third param"];
$query ="first text ? other text ? other chunk ?";

预期输出是:

first text first param other text  second param ? other chunk third param
^^^^^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^
first placeholder second placeholder third placeholder

我的自定义解决方案

我已经使用 preg_split 提出了一个可能的解决方案,但老实说,这太老套了,必须有更好的东西:

 $parts = preg_split('/(\?)/', $query, -1, PREG_SPLIT_DELIM_CAPTURE);

foreach($parts as $k=>&$v) {
// if is odd, then it's a placeholder
if ($k%2 == 1)
$v = $params[$k/2]; // replace placeholder with a param
}

$query = implode('',$parts);

最佳答案

任何自定义替换逻辑都应使用 preg_replace_callback 实现,例如:

$params = ["first param", "second param ?", "third param"];
$query ="first text ? other text ? other chunk ?";

echo preg_replace_callback('/\?/', function($m) use (&$params) {
return array_shift($params);
}, $query);

实时代码:http://sandbox.onlinephpfunctions.com/code/33f4804b49103e54e8070e8d9959ec9642930857

关于php - 避免替换替换字符串中找到的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56713856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com