php - PHP For循环迭代应该调整
问题描述
我有一个 for 循环,旨在从我提供给它的不同字符串中提取所有数字。我将提取的数字保存在一个数组中。我的代码如下:
$length = strlen($RouteString);
$data = [];
$index = 0;
for($i = 0; $i < $length; $i++)
{
$j = 1;
$count = 0;
while(is_numeric(substr($RouteString,$i,$j)) == true)
{
$data[$index] = substr($RouteString,$i,$j);
$j = $j+1;
}
if(is_numeric(substr($RouteString,$i,1)) == true)
{
$index = $index + 1;
}
}
$Routestring
设置为:"B12-1234-U102-D4-11-19-E"
并且应该给出结果,$data=[12,1234,102,4,11,19]
但它给出了$data=[12,2,1234,234,34,4,102,02,2,4,11,1,19,9]
.
我尝试通过调整来解决问题,$index
但它不起作用。我不知道如何解决这个问题。
任何建议将不胜感激
解决方案
有很多方法可以更轻松地做到这一点,这里有一个:
preg_match_all('/\d+/', $string, $matches);
匹配 1 个或多个数字\d+
。你的数组将在$matches[0]
.
推荐阅读
- sql - 以 yyyy-mm-dd 格式获取上一年第一个月的第一天
- python - 如何优化python列表中的比较组合
- java - 使用 mongoDB 的 Spring Boot 返回 NullPointerException
- excel - 无法识别日期
- javascript - PHP $_GET 值未从 jQuery AJAX 调用中提取 - PHP 包含问题?
- mysql - withCount() - 获得 2 个计数的差值
- php - 如何使用 REST API 为 WooCommerce 产品指定产品图像排序顺序?
- python - Pyinstaller 生成空 dist 文件夹
- javascript - 在 React Native 上调节按钮
- python - 将多个 Vega/vincent 图表添加到 Folium 弹出窗口