我目前正在尝试在PHP中创建一个随机图像生成器,并且我很难设置文件路径,我可以获取所有文件路径,但它们在一个长字符串中,就像这样。
" ../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG"
," .."
标记新文件的开头。
我如何将每个file_path爆炸(或类似的东西)分别返回它们?
答案 0 :(得分:2)
这是一种可以做到这一点的方法。
$data = '../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG';
$files = preg_split('/(?<!^)(?=\.{2})/', $data);
print_r($files);
输出
Array
(
[0] => ../images/box1/IMG_3158.JPG
[1] => ../images/box1/IMG_3161.JPG
[2] => ../images/box1/IMG_3163.JPG
[3] => ../images/box1/IMG_3158.JPG
[4] => ../images/box1/IMG_3161.JPG
[5] => ../images/box1/IMG_3163.JPG
)
正则表达式:
(?<! look behind to see if there is not:
^ the beginning of the string
) end of look-behind
(?= look ahead to see if there is:
\.{2} '.' (2 times)
) end of look-ahead
答案 1 :(得分:2)
<?php
//Since new file path is starting from ".." we explode it using ".." and added to each file path.
$string ="../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG";
$file_path=explode('..',$string);
$i=0;
while(isset($file_path[++$i])){
$file_path[$i]="..".$file_path[$i];
echo $file_path[$i]."<br />";
}
?>
答案 2 :(得分:1)
只需使用explode()
$file_paths = explode('..', $input);
示例强>
$string = "../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG../images/box1/IMG_3158.JPG../images/box1/IMG_3161.JPG../images/box1/IMG_3163.JPG";
$file_paths = explode('..', $string);
var_dump($file_paths);
开头的".."
条,所以请尝试自己添加。对于更复杂的情况,preg_split()
将是一项适当的任务。鉴于你的字符串没有改变,那么爆炸就可以了。
答案 3 :(得分:0)
如果您在导入(?)路径名列表时能够在每个路径之间引入一个未使用的字符,则可以将该字符用作分隔符而不是&#34; ..&#34; (参考阿里的答案)。