Search code examples
phpmultilinetext-extractiontext-parsing

Populate two arrays from substrings in multiline text


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 do 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.


Solution

  • 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.