我有一个这种格式的.txt文件:
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
我需要得到一个像这样的数组:
[ZA-98765-4321098-API, ZA-12345-6789012-API, etc]
我在python中尝试了一些东西,但我意识到我没有在计算机中安装它(一直在使用repl.it)有没有办法在php中执行此操作?
答案 0 :(得分:2)
看看这是否适合你:
<?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);
Array
(
[0] => MP-98765-4321098-API
[1] => MP-12345-6789012-API
[2] => MP-23456-7890123-API
[3] => MP-01234-5678901-API
)
答案 1 :(得分:2)
简单的正则表达式怎么样:
preg_match_all('/Order Number: (.*)/', file_get_contents('/path/to/file.txt'), $matches);
$result = $matches[1];
如果你想在最后捕获换行符,那么一种可能的模式是:
/Order Number: (.*\n?)/
答案 2 :(得分:1)
与Python一样,您可以使用生成器(在处理大文件时很有用,并且您希望保留内存):
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);
}