加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何使用方括号中指定的FROM和TO数字用PHP扩展字符串?

发布时间:2020-12-13 16:52:00 所属栏目:PHP教程 来源:网络整理
导读:假设我有字符串http://www.example.com/images/[1-12].jpg.我想将其扩展为: http://www.example.com/images/1.jpg http://www.example.com/images/2.jpg http://www.example.com/images/3.jpg http://www.example.com/images/4.jpg http://www.example.com/
假设我有字符串http://www.example.com/images/[1-12].jpg.我想将其扩展为:

http://www.example.com/images/1.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
http://www.example.com/images/5.jpg
http://www.example.com/images/6.jpg
http://www.example.com/images/7.jpg
http://www.example.com/images/8.jpg
http://www.example.com/images/9.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/12.jpg

这是我的代码:

$str = "http://www.example.com/images/[1-12].jpg";
while(preg_match_all("/^([^[]]*)[(d+)-(d+)](.*)$/m",$str,$mat)){
$arr = array();
$num = sizeof($mat[0]);
    for($i = 0; $i < $num; $i++){
        for($j = $mat[2][$i]; $j <= $mat[3][$i]; $j++){
        $arr[] = rtrim($mat[1][$i].$j.$mat[4][$i]);
        }
    }
$str = implode(PHP_EOL,$arr);
}

即使我将$str更改为更复杂的表达式,它仍然可以正常工作,如下所示:

$str = "http://www.example.com/images/[1-4]/[5-8]/[9-14].jpg";

但遗憾的是,不支持零填充整数.所以,如果我开始:

$str = "http://www.example.com/images/[001-004].jpg";

预期结果:

http://www.example.com/images/001.jpg
http://www.example.com/images/002.jpg
http://www.example.com/images/003.jpg
http://www.example.com/images/004.jpg

而实际结果如下:

http://www.example.com/images/001.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg

如何更改此行为,以便我的代码产生预期的结果?另外,我的代码的其他缺点是什么?我应该真的使用while循环和preg_match_all,还是有更快的替代品?

更新:将我的代码的第七行更改为

$arr[] = rtrim($mat[1][$i].str_pad($j,strlen($mat[2][$i]),STR_PAD_LEFT).$mat[4][$i]);

似乎可以做到这一点.非常感谢sjagr提出这个建议.我的问题仍然存在,因为我想知道我的代码和更快的替代品(如果有的话)的缺点.

解决方法

根据@ SoumalyoBardhan的要求,我的建议/答案:

如果使用str_pad(),则可以使用匹配找到的strlen()根据匹配字符串的大小强制填充.你对它的使用对我来说很好看:

$arr[] = rtrim($mat[1][$i].str_pad($j,STR_PAD_LEFT).$mat[4][$i]);

我真的看不出还有什么可以用你的代码改进,虽然我不完全理解如何在while语句中使用preg_match_all.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读