php - 如何用数组填充所有 preg_match()
问题描述
我有一个字符串"1 + 1 = 12, wrong"
和一个数组[1, 2, 3, 'correct']
以及正则表达式模式/(\d+) + (\d+) = (\d+), (\w+)/
如何将匹配的结果填充到数组值中。
所以字符串将是"1 + 2 = 3, correct"
解决方案
一个可能的解决方案 - 也许不是最好的- 是循环遍历您匹配的内容preg_match()
,并逐个替换。
$str = '1 + 1 = 12, wrong';
$pattern = '/(\d+) \+ (\d+) = (\d+), (\w+)/';
$replacer = [1, 2, 3, 'correct'];
$result = $str;
if (preg_match($pattern, $result, $matches)) {
// If there is enough matches, we can continue
if (sizeof($matches) === (sizeof($replacer) + 1)) {
// We begin at 1 because $matches[0] is the whole string.
for ($i = 1; $i < sizeof($matches); $i++) {
// We use preg_replace because str_replace will replace all occurences of the match.
$result = preg_replace('/' . $matches[$i] . '/', $replacer[$i - 1], $result, 1);
}
}
}
请注意,我更正了您的正则表达式模式。
推荐阅读
- xcode - Bazel 无法运行 xcrun 但 xcode 和 xcrun 已在本地正确安装
- php - 是否可以使此 ASP.NET 到 ASP.NET SSO 功能与 ASP.NET 到 PHP 一起使用?
- javascript - 为什么一个反斜杠的 JSON.parse 返回两个反斜杠,而不是四个反斜杠
- vowpalwabbit - cb_explore 输入格式:在训练中使用提供概率值
- python - 如何使两台印刷机在 tkinter 中产生相同的输出
- javascript - 将 javascript 按钮添加到模态(javascript 新手)
- amp-html - AMP 中有没有办法在上传之前从输入表单中显示选定的图像?
- javascript - 如何修复此 jquery 安全警报:“您的应用包含一个或多个存在已知安全问题的库”
- python - 获取条形图中条形的标签
- ruby - 当我使用类 httparty 时,我遇到了 parsed_response 的问题