我正在尝试循环preg_match_all()
的结果并更换火柴。
我想要实现的是提取大括号之间的文本中前面有美元符号的所有出现次数,然后创建一个 <span>
id 是大括号内的内容。
因此,在下面的示例中,从文本“每天从 ${spa_open_time} 工作到 ${spa_close_time}”中,我应该提取 ${spa_open_time}
和${spa_close_time}
并将文本中的它们替换为 <span>
.
预期结果
Working from <span id="tag_spa_open_time">${spa_open_time}</span> to <span id="tag_spa_close_time">${spa_close_time}</span> every day
这是我到目前为止想到的代码
$text = 'Working from ${spa_open_time} to ${spa_close_time} every day';
$result = preg_match_all('/(\$\{\w+\})/', $text, $positive_catch);
if ($result > 0) {
foreach ($positive_catch as $catch) {
if (is_array($catch)) {
foreach ($catch as $key => $ivalue) {
$fvalue = str_replace("\${", "", $ivalue);
$fvalue = str_replace("}", "", $fvalue);
$replace = '<span id="tag_'.$fvalue.'">'.$ivalue.'</span>';
$str = str_replace($catch,$replace,$text);
}
}
}
} else {
$str = $text;
}
echo $str;
当前结果是
Working from <span id="tag_spa_close_time"><span id="tag_spa_close_time">${spa_close_time}</span></span> to <span id="tag_spa_close_time">${spa_close_time}</span> every day
我做错了什么,但我不知道问题出在哪里。 这是正在运行的代码 http://sandbox.onlinephpfunctions.com/code/31894399fd981fb791c587fa04c68581c4945b6d
最佳答案
我已经修改了您的正则表达式以返回要搜索的字符串(例如“${spa_open_time}”)和“键”(例如“spa_open_time”)。然后,我同时循环这些数组,并生成一对搜索和替换字符串,并将其应用于 $str
,每次都会进行修改。在循环结束时,$str
包含您的结果。
$str = $text = 'Working from ${spa_open_time} to ${spa_close_time} every day';
$result = preg_match_all('/\$\{(\w+)\}/', $text, $positive_catch);
if ($result > 0) {
for ( $i=0; $i < sizeof($positive_catch[0]); $i++ ) {
$search = $positive_catch[0][$i];
$key = $positive_catch[1][$i];
$replace = '<span id="tag_' . $key . '">' . $search . '</span>';
$str = str_replace($search, $replace, $str);
}
} else {
$str = $text;
}
echo $str;
`
关于php - 循环 preg_match_all 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70473353/