Onilol
Onilol

Reputation: 1339

Slicing from text file

I have a .txt file in this format:

Order pushed to ZA!
Order Number: ZA-98765-4321098-API

Order pushed to ZA!
Order Number: ZA-12345-6789012-API

Order pushed to ZA!
Order Number: ZA-23456-7890123-API

Order pushed to ZA!
Order Number: ZA-01234-5678901-API

I need to end up with an array like this :

[ZA-98765-4321098-API, ZA-12345-6789012-API, etc]

I've tried some stuff in python but I realized I don't have it installed in the computer ( been using repl.it ) is there a way to do this in php?

Upvotes: 2

Views: 55

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

How about a simple regex:

preg_match_all('/Order Number: (.*)/', file_get_contents('/path/to/file.txt'), $matches);
$result = $matches[1];

If you want to capture the newlines at the end then one possible pattern is:

/Order Number: (.*\n?)/

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

As with Python, you can use a generator (useful when you deal with a big file and you want to preserve memory):

function genOrderNumbers($fh) {
    while (($line = fgets($fh)) !== false) {
        if (strpos($line, 'Order Number: ') === 0)
            yield rtrim(substr($line, 14));
    }
}

$fh = fopen('inputfile.txt', 'r');
if ($fh) {
    foreach (genOrderNumbers($fh) as $orderNumber)
        echo $orderNumber, PHP_EOL;
    fclose($fh);
}

Upvotes: 1

Dave Chen
Dave Chen

Reputation: 10975

See if this works for you:

<?php

function getBetween($a, $b, $c) {
    $y = explode($b, $a);
    $len = sizeof($y);
    $arr = array();
    for ($i = 1; $i < $len; $i++) {
        $el = explode($c, $y[$i]);
        $arr[] = $el[0];
    }
    return $arr;
}

$data = 'Order pushed to ZA!
Order Number: ZA-98765-4321098-API

Order pushed to ZA!
Order Number: ZA-12345-6789012-API

Order pushed to ZA!
Order Number: ZA-23456-7890123-API

Order pushed to ZA!
Order Number: ZA-01234-5678901-API';

$final = getBetween($data, 'ZA-', '-API');
foreach ($final as &$value)
    $value = 'ZA-' . $value . '-API';

print_r($final);

Output:

Array
(
    [0] => MP-98765-4321098-API
    [1] => MP-12345-6789012-API
    [2] => MP-23456-7890123-API
    [3] => MP-01234-5678901-API
)

Upvotes: 2

Related Questions