![](/img/trans.png)
[英]Get content between two words - preg_match_all multiple patterns
[英]Get a word between two patterns in preg_match_all
我正在嘗試從以下字符串中獲取下載的百分比值。
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4
[download] 100% of 1.60MiB in 00:21
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a
[download] 100% of 164.86KiB in 00:01
對於前。 '100' between '[download]' and '% of'
僅取值'100' between '[download]' and '% of'
。 這是到目前為止我嘗試過的代碼
$file = file_get_contents("t.txt");
if (preg_match_all("/(?<=\[download\])(.*?)(?=\% of)/s", $file, $result))
for ($i = 1; count($result) > $i; $i++) {
print_r($result[$i]);
}
但是問題是它從第一行抓起,輸出像
Array ( [0] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4 [download] 100 [1] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a [download] 100 )
我想,如果我能搶在'% of'
之前就可以了。 我應該堅持使用此代碼來修改或更改整個模式嗎?
這應該為您工作:
在這里,我首先使用file()
將文件放入數組,其中每一行都是一個數組元素。 在那里,我忽略了換行符和空行。
之后,我使用array_map()
遍歷每一行, array_map()
使用preg_match_all()
檢查是否存在以下模式: [download] (\\d+)% of
。 如果找到該數字,則返回該數字,否則返回false,最后使用array_filter()
過濾出具有false的元素。
<?php
$lines = file("t.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$numbers = array_filter(array_map(function($v){
if(preg_match_all("/\[download\] (\d+)% of/", $v, $m))
return $m[1][0];
else
return false;
}, $lines));
print_r($numbers);
?>
輸出:
Array ( [1] => 100 [3] => 100 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.