简体   繁体   English

php正则表达式在文件中查找字符串

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

I am trying to make a php script to output all values inside an hypehref=" * * " from a text file. 我正在尝试制作一个php脚本,以从文本文件中输出hypehref =“ * *”内的所有值。

I'm having a hard time with the regular expression part. 我正则表达式部分很难。

This is what I have 这就是我所拥有的

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

My result is this : 我的结果是这样的:

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
)

The [0] is incorrect, it includes the part I am searching for... all I want is the result after the hypehref=" [0]不正确,它包括我要搜索的部分...我想要的只是hypehref =“之后的结果

The second result [1] is correct 第二个结果[1]是正确的

and my file should have given me about 10 results.. not just 2... 并且我的文件应该给了我大约10个结果..不只是2个...

Any ideas why ? 有什么想法吗? Thx 谢谢

You can use preg_match_all to find all matches. 您可以使用preg_match_all查找所有匹配项。 There you will also have the full part and only the value of the hyperef - but you can only use the former. 在那里,您还将拥有hyperef的全部内容和价值-但您只能使用前者。

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

I added the if for obvious reasons and the i delimiter, so the pattern will ignore case sensitivity. 由于明显的原因,我添加了ifi分隔符,因此该模式将忽略大小写。

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

var_dump($ora_books);

example 2 例子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