繁体   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