【问题标题】:php search text file for any wav file namesphp 在文本文件中搜索任何 wav 文件名
【发布时间】:2019-05-08 12:51:59
【问题描述】:

我有一系列包含原始文本或 json 数据的文件,在这些文件中将是 wav 文件名。所有wav文件的后缀都是.wav

无论如何使用 php 我可以搜索单个文本或 json 文件并返回找到的任何 .wav 文件的数组?

此随机文本示例包含 6 个 .wav 文件,我将如何搜索并提取文件名?

Spoke as as other again ye. Hard on to roof he drew. So sell side newfile.wav ye in mr evil. Longer waited mr of nature seemed. Improving knowledge incommode objection me ye is prevailed playme.wav principle in. Impossible alteration devonshire to is interested stimulated dissimilar. To matter esteem polite do if. 

Spot of come to ever test.wav hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated welcome.wav especially. Unfeeling one provision are smallness resembled repulsive. 

Raising say express had chiefly detract demands she. Quiet led own cause three him. Front no party young abode state up. Saved he do fruit woody of to. Met defective are allowance two perceived listening consulted contained. It chicken oh colonel pressed excited suppose to shortly. He improve started no we manners another.wav however effects. Prospect humoured mistress to by proposal marianne attended. Simplicity the far admiration preference everything. Up help home head spot an he room in. 

Talent she for lively eat led sister. Entrance strongly packages she out rendered get quitting denoting led. Dwelling confined improved it he no doubtful raptures. Several carried through an of up attempt gravity. Situation to be at offending elsewhere distrusts if. Particular use for considered projection cultivated. Worth of do doubt shall it their. Extensive existence up me last.wav contained he pronounce do. Excellence inquietude assistance precaution any impression man sufficient. 

我试过了,但没有结果。

$lines = file('test.txt');

foreach ($lines as $line_num => $line) {

    $line = trim($line);

    if (strpos($line, '*.wav') !== false) {
        echo ($line);
    }

}

上面的文字应该返回:

newfile.wav
playme.wav
test.wav
welcome.wav
another.wav
last.wav

谢谢

更新:

使用以下内容:

$text = file_get_contents('test.txt');
preg_match_all('/\w+\.wav/', $text, $matches);
var_dump($matches);

产生一个数组:

    array(1) {
      [0]=>
      array(6) {
        [0]=>
        string(11) "newfile.wav"
        [1]=>
        string(10) "playme.wav"
        [2]=>
        string(8) "test.wav"
        [3]=>
        string(11) "welcome.wav"
        [4]=>
        string(11) "another.wav"
        [5]=>
        string(8) "last.wav"
      }
}

所以数组中包含 wav 文件的数组,我如何获得 wav 文件的数组?谢谢

这不适用于名称中带有空格的 wav 文件。 有什么想法吗?

【问题讨论】:

  • if (strpos($line, '*.wav')更改为if(strpos($line, '.wav')
  • 你也打印整行?
  • 使用preg_match_all('~\S+\.wav\b~', $text, $matches)print_r($matches[0])可能会看到结果。您需要将文件作为单个字符串读取,但要使其正常工作,请使用$text = file_get_contents('test.txt');

标签: php regex search


【解决方案1】:

This tool 可能会帮助您根据需要设计表达式并对其进行测试,可能类似于:

([a-z]+\.wav)

如果您愿意,还可以为其添加更多边界。

这里]2]2

图表

此图显示了表达式的工作原理,您可以在此 link 中可视化其他表达式:

PHP 代码

您也可以使用preg_match_all 来执行此操作,可能类似于:

$re = '/([a-z]+\.wav)/m';
$str = 'Spoke as as other again ye. Hard on to roof he drew. So sell side newfile.wav ye in mr evil. Longer waited mr of nature seemed. Improving knowledge incommode objection me ye is prevailed playme.wav principle in. Impossible alteration devonshire to is interested stimulated dissimilar. To matter esteem polite do if.

    Spot of come to ever test.wav hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated welcome.wav especially. Unfeeling one provision are smallness resembled repulsive.

    Raising say express had chiefly detract demands she. Quiet led own cause three him. Front no party young abode state up. Saved he do fruit woody of to. Met defective are allowance two perceived listening consulted contained. It chicken oh colonel pressed excited suppose to shortly. He improve started no we manners another.wav however effects. Prospect humoured mistress to by proposal marianne attended. Simplicity the far admiration preference everything. Up help home head spot an he room in.

    Talent she for lively eat led sister. Entrance strongly packages she out rendered get quitting denoting led. Dwelling confined improved it he no doubtful raptures. Several carried through an of up attempt gravity. Situation to be at offending elsewhere distrusts if. Particular use for considered projection cultivated. Worth of do doubt shall it their. Extensive existence up me last.wav contained he pronounce do. Excellence inquietude assistance precaution any impression man sufficient. ';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

正则表达式测试脚本

const regex = /([a-z]+\.wav)/gm;
const str = `Spoke as as other again ye. Hard on to roof he drew. So sell side newfile.wav ye in mr evil. Longer waited mr of nature seemed. Improving knowledge incommode objection me ye is prevailed playme.wav principle in. Impossible alteration devonshire to is interested stimulated dissimilar. To matter esteem polite do if.
    
    Spot of come to ever test.wav hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by. On no am winding chicken so behaved. Its preserved sex enjoyment new way behaviour. Him yet devonshire celebrated welcome.wav especially. Unfeeling one provision are smallness resembled repulsive.
    
    Raising say express had chiefly detract demands she. Quiet led own cause three him. Front no party young abode state up. Saved he do fruit woody of to. Met defective are allowance two perceived listening consulted contained. It chicken oh colonel pressed excited suppose to shortly. He improve started no we manners another.wav however effects. Prospect humoured mistress to by proposal marianne attended. Simplicity the far admiration preference everything. Up help home head spot an he room in.
    
    Talent she for lively eat led sister. Entrance strongly packages she out rendered get quitting denoting led. Dwelling confined improved it he no doubtful raptures. Several carried through an of up attempt gravity. Situation to be at offending elsewhere distrusts if. Particular use for considered projection cultivated. Worth of do doubt shall it their. Extensive existence up me last.wav contained he pronounce do. Excellence inquietude assistance precaution any impression man sufficient. `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

【讨论】:

  • 这似乎对我不起作用..我不明白为什么
  • 我还没有得到这个工作..它将如何处理名称中带有空格的文件?
【解决方案2】:

这就是regular expressions 被发明的原因。

$text = file_get_contents('test.txt');
preg_match_all('/(\w+\.wav)/', $text, $matches);
var_dump($matches[0]);

一些不错的资源:

输出:

    array(6) {
      [0] => string(11) "newfile.wav"
      [1] => string(10) "playme.wav"
      [2] => string(8) "test.wav"
      [3] => string(11) "welcome.wav"
      [4] => string(11) "another.wav"
      [5] => string(8) "last.wav"
    }

【讨论】:

  • 应该使用 preg_match_all。
  • 为什么对此投反对票?它似乎有效,我很好奇它是否会引起问题?
  • 这确实有效,但提供了一个数组中的文件数组。我如何只返回文件数组?
  • @Rocket 如果您不需要这些职位,请使用 $matches[0] 作为结果。
  • @PeterRakmanyi 感谢这很好用,除非 wav 文件的名称中有空格。有什么办法处理吗?
【解决方案3】:

你快到了。您可以按空格分解$line。现在,您检查每个单词并检查是否以 .wav 扩展名结尾。如果是,则打印该单词。

<?php

foreach ($lines as $line_num => $line) {
    $line = trim($line);
    $words = explode(" ",$line);
    foreach($words as $each_word){
        $wav_index = strpos($each_word, '.wav');
        if ($wav_index !== false && $wav_index === strlen($each_word) - 4) { // strict check to make sure string ends with a .wav and not being elsewhere
            echo $each_word,PHP_EOL;
        }
    }    
}

【讨论】:

  • 是否在空格处爆炸行,然后搜索添加任何额外负载?
  • @Tom 这可能需要一些额外的内存,但可以忽略不计。
  • @vivek_23 我遇到的问题是 wav 文件的名称中可能有空格。有什么办法处理吗?
  • @Rocket 你能告诉我你是如何得到这些数据的吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多