我有多个带有相同花括号的字符串,如果计数为1,则希望将其替换为动态字符串,然后需要替换第一个匹配项;如果计数为2,则替换第二个匹配项,以此类推,直到条件满足为止.
include_once("con.php");
$db = new Da();
$con = $db->con();
$String = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";
$Count = 1;
if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {
foreach ($matches[0] as $match) {
$Count++;
$Query = "SELECT link FROM student WHERE linkVal = '".$match."'";
$Result = $con->query($Query);
if($row = $Result->fetch(PDO::FETCH_ASSOC)) {
$NewValue = preg_replace("/\{\{[^{}]+\}\}/", $row["link"], $String);
}
}
echo json_encode($NewValue);
}
?>
如果第一次出现,{{ONE}}应该用$row [“ link”]替换为新值,
其次,用新值替换{{TWO}},以此类推.
解决方法:
在每次比赛的循环中,建议不要使用str_replace而不是使用preg_replace:
if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {
$NewValue = $String;
foreach ($matches[0] as $match) {
$Count++;
$Query = "SELECT link FROM student WHERE linkVal = '".$match."'";
$Result = $con->query($Query);
if($row = $Result->fetch(PDO::FETCH_ASSOC)) {
$NewValue = str_replace($match, $row["link"], $NewValue);
// ^^^^^^^^^^^^^^^^^^
}
}
echo json_encode($NewValue);
}
标签:preg-match-all,php,regex,preg-replace,regex-group
来源: https://codeday.me/bug/20191011/1894650.html