【问题标题】:How Do you split a string like this? PHP你如何分割这样的字符串? PHP
【发布时间】:2014-06-06 05:05:59
【问题描述】:

我目前正在尝试在 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 以分别返回它们?

【问题讨论】:

  • 我认为这是 PHP?
  • 是的,为了清晰起见,我在标题和标签中添加了 PHP。谢谢。
  • 为什么文件路径在一开始就是这样的一个长字符串?你是怎么得到它们的,为什么它们不在一个数组中?

标签: php arrays string explode


【解决方案1】:

这是您可以做到这一点的一种方法。

$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

【讨论】:

  • 如果您不介意,能否请您解释一下正则表达式,它看起来对男性来说令人印象深刻,请不要发布http://liveforfaith.com/re/explain.pl 的结果,哈哈。需要更多的细分
  • @shatheesh 它首先向后看以确保没有字符串的开头,因此我们在拆分时不会捕获空结果,而它向前看标记..之前的位置跨度>
【解决方案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 />";

      }

   ?>

【讨论】:

    【解决方案3】:

    http://ideone.com/MTRr9Q

    只需使用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() 将是一个合适的任务。鉴于你的字符串没有改变,那么爆炸就可以了。

    【讨论】:

    • 是的,当我问这个问题时,我有点震惊,我只是看不到在哪里可以找到创建分隔符的引用。 ----- 如果这些点不存在,你会怎么做?
    • 嗯,第一个参数是分隔符,代替“..”,无论分隔符是什么,它都可以是一个“.”。或“-”或其他任何内容
    • 啊,好的。谢谢我会玩这个!
    【解决方案4】:

    如果您能够在导入(?)路径名称列表时在每个路径之间引入一个其他未使用的字符,那么您可以使用该字符作为分隔符而不是“..”(请参阅​​ Ali 的回答)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多