PHP:在文件中查找字符串并打印下几个字符

时间:2017-04-27 14:03:34

标签: php

[amount] = "58"

我有一个大文本文件,我正在尝试查找金额发生的位置并打印58,因为我在多个页面上抓取HTML,所有页面都有类似的布局,但每个页面上的金额值都会发生变化。唯一的常量是字符串[amount]出现一次,所以我可以用它来查找数字值。 我想知道如何在PHP中执行此操作。

感谢。

我试过的代码是

$filename = 'site.txt';

$searchfor = '[amount]';

$file = file_get_contents($filename);

if(strpos($file, $searchfor [$offset = 6]))
{
    echo $searchfor;
}

2 个答案:

答案 0 :(得分:0)

$filename = 'site.txt'; 
$searchfor = '[amount] = "'; 
$file = file_get_contents($filename); 
//find the position
$pos = strpos($file, $searchfor);
//check for real false here
if($pos!==false) { 
   //print from the found postion+lengthofserachfor
   //(int) makes an real number if you get '6 abc' an real 6
   echo (int)substr($file,$pos+strlen($searchfor),5); 
} 

到目前为止,完成了。

if(preg_match('#amount\][ ]?=[ ]?"([0-9]+)#',$file,$matches)){
    print_r($matches);
}

度过愉快的一天。

答案 1 :(得分:0)

我想你想找到数字58,这可以做到,例如。

输入为site.txt

some text [amount] = "58" some other text

在cli上运行:php test.php

<?php

$filename = './site.txt';
$searchfor = '[amount]';
$file = file_get_contents($filename);

foreach( explode("\n", $file) as $line ){
    $found = strpos($line, $searchfor);
    if($found){
        echo "string found on position: ".$found." in '" . $line. "'\n";
        echo "so the searched stuff should be: '" . explode('"', substr($line,$found,strlen($line)-$found))[1] ."'\n";
    }
}

?>

导致输出:

string found on position: 10 in 'some text [amount] = "58" some other text'
so the searched stuff should be: '58'