Marco
Marco

Reputation: 867

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.

Upvotes: 0

Views: 94

Answers (3)

raina77ow
raina77ow

Reputation: 106385

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.

Upvotes: 2

hakre
hakre

Reputation: 197757

First of all split the string into each line (by the line ending character).

Then split each line into two parts at the first - and add those parts to the result. You can later on give each part a name on it's own:

Example/Demo:

$lines = explode("\r\n", $sitesinfo);
$r = array(null, null);
foreach($lines as $line) {
    list($r[0][], $r[1][]) = explode("-", $line, 2) + array(1 => NULL);
}
list($titles, $domains) = $r;
unset($r);

Or the regex variant (Demo):

preg_match_all('~([^-]+)-(.*)~', $sitesinfo, $matches);
list(, $titles, $domains) = $matches;
unset($matches);

Result:

array(5) {
  [0]=>
  string(13) "site 1 titles"
  [1]=>
  string(13) "site 2 titles"
  [2]=>
  string(13) "site 3 titles"
  [3]=>
  string(13) "site 4 titles"
  [4]=>
  string(13) "site 5 titles"
}
array(5) {
  [0]=>
  string(13) "example1.com/"
  [1]=>
  string(13) "example2.com/"
  [2]=>
  string(13) "example3.com/"
  [3]=>
  string(13) "example4.com/"
  [4]=>
  string(13) "example5.com/"
}

Upvotes: 1

CrayonViolent
CrayonViolent

Reputation: 32532

regex alternative:

$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/';

preg_match_all('~([^-]+)-(.*)~',$sitesinfo,$matches);
$titles = array_map('trim',$matches[1]);
$domains = array_map('trim',$matches[2]);

Upvotes: 1

Related Questions