需要把字符串中的 {$amount}, {$project} ... 替换为 {$code}
不知道用preg_replace怎么做
* preg.php
<?php
include dirname(__FILE__).'/Str.php';
$s = "您的奖励元已到账,请登录会员中心查看!【xxxx】{\$amount}";
// 把模板变量名替换为code
// $t = Str::replaceBetween($s, 'code', "{\$", "2}");
$t = Str::replaceBetween($s, 'code', "{\$", "}");
var_dump($t);
$s = '您???的{$project}???已成功!【xxxx】';
$t = Str::replaceBetween($s, 'code', "{\$", "}");
var_dump($t);
* Str.php
<?php
/**
* Created by PhpStorm.
* User: Mch
* Date: 2019-11-24
* Time: 12:59
*/
class Str
{
/**
* 把字符串$s ${xxx} 中间的内容替换成 ${yyy}
* @param $s string 替换前的整个字符串
* @param $repe string 用来替换的部分字符串
* @param string $open ${
* @param string $close }
* @return string
*/
public static function replaceBetween($s, $rep, $open = "\${", $close = "}") {
$i = self::findIndexFollowDelim($s, $open, 0);
$j = self::findIndexFollowDelim($s, $close, $i);
// not found
if ($i < 0 || $j < 0) {
return $s;
}
return substr($s, 0, $i).$rep.substr($s, $j-1);
}
private static function findIndexFollowDelim($s, $delim, $startAt=0) {
$n = strlen($delim);
$j = 0;
for ($i = $startAt; isset($s[$i]) && $j < $n; $i++) {
if ($delim[$j] === $s[$i]) {
$j += 1;
} else {
$j = 0;
}
}
if (!isset($s[$i]) && $j < $n) {
return -1;
}
return $i;
}
}
* test:
$ php preg.php
string(82) "您的奖励元已到账,请登录会员中心查看!【xxxx】{$code}"
string(55) "您??的{$code}??已成功!【xxxx】"