簡體   English   中英

php正則表達式在文件中查找字符串

[英]php regular expression to find a string in a file

我正在嘗試制作一個php腳本,以從文本文件中輸出hypehref =“ * *”內的所有值。

我正則表達式部分很難。

這就是我所擁有的

$Vdata = file_get_contents('file.txt');
preg_match( '/hyperef="(.*?)"/', $Vdata, $match );
echo '<pre>'; print_r($match); echo '</pre>'

我的結果是這樣的:

Array
(
    [0] => hyperef="http://lookbook.nu/look/5709720-Choies-Silvery-Bag-Rosewholesale-Punk-Style/hype"
    [1] => http://lookbook.nu/look/5709720-Choies-Silvery-Bag-Rosewholesale-Punk-Style/hype
)

[0]不正確,它包括我要搜索的部分...我想要的只是hypehref =“之后的結果

第二個結果[1]是正確的

並且我的文件應該給了我大約10個結果..不只是2個...

有什么想法嗎? 謝謝

您可以使用preg_match_all查找所有匹配項。 在那里,您還將擁有hyperef的全部內容和價值-但您只能使用前者。

if (preg_match_all('/hyperef="(.*?)"/i', $Vdata, $result)) {
    $matches = $result[1]; //only values inside quotation marks
    print_r($matches);
} else
    print "nothing found";

由於明顯的原因,我添加了ifi分隔符,因此該模式將忽略大小寫。

$pattern = "/\bo'reilly\b/i"; // only O'Reilly
$ora_books = preg_grep($pattern, file('filed.txt'));

var_dump($ora_books);

例子2

$fh = fopen('/path/to/your/file.txt', 'r') or die($php_errormsg);
while (!feof($fh)) {
$line = fgets($fh);
if (preg_match($pattern, $line)) { $ora_books[ ] = $line; }
}
fclose($fh);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM