douliang9057 2012-06-24 00:11
浏览 46
已采纳

将字符串拆分成多个数组?

i have a string like this one

$sitesinfo = 'site 1 titles-example1.com/
site 2 titles-example2.com/
site 3 titles-example3.com/
site 4 titles-example4.com/
site 5 titles-example5.com/';

i used to split lines into 1 array like this

$lines = explode("/",$sitesinfo);

then while i loop i got each line into an array object without problems what i need to do to split each line into 2 pieces and add each piece into an array so the result be like this

$titles = array("site 1 titles","site 2 titles","site 3 titles","site 4 titles","site 5 titles");
$domains = array("example1.com","example2.com","example3.com","example4.com","example5.com");

so i can use them in script

i did a lot of tries but fail :(

Thanks

  • 写回答

3条回答 默认 最新

  • dtvpl739577 2012-06-24 00:13
    关注

    How about this:

    foreach ($lines as $line) {
      $t = explode('-', trim($line), 2);
      if (count($t) < 2) {
        echo "Failed to parse the line $line";
        continue;
      }
      $titles[] = $t[0];
      $domains[] = $t[1];
    }
    

    Explanation: each line split by '-' symbol into exactly 2 parts (if there's less, that's an error - the line doesn't contain '-', and thus shouldn't be processed at all). The first part is pushed into $titles array, the second - into $domains.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里