PHP从文本文件中读取字符串

时间:2016-02-14 18:23:29

标签: php html

您好我需要从文本文件中提取一些图像链接。 它应该存储在一些变量中,因此可以重用链接。 我只需要以image1.jpg

结尾的img文件

我使用了这段代码

<?php
    $myfile = fopen("vwe/autos.inc", "r") or die("Unable to open file!");

    // Output one line until end-of-file
    while(!feof($myfile)) {

        $photo1 = fgets($myfile);
        //echo var_export(substr($photo1, 0, 30))."<br>";

        echo "1)".substr($photo1, 10, 30)."<br>";
        echo "2)".substr($photo1, 40, 80)."<br>";
    }

    close($myfile);
?>

Autos.inc看起来像这样:

<div class='glidecontent'>
    <div id='positiontest'>
        <a href='occasion.aspx' target='_self'>
            <img src='http://site.nl/643607012/image1.jpghttp://sit.nl/643607013/image2.jpghttp://site.nl/643607014/image3.jpg' width='100%' border='0' height='100%' style='float: top; padding: 0px' />
        </a>
        <div id='textonadd'>
            <b>Citro&#235;n C3</b>&nbsp;1.4i Diff&#233;rence</br>
            Bouwjaar: 2004 | Prijs: 3250 euro
        </div>
    </div>
</div>

<div class='glidecontent'>
    <div id='positiontest'>
        <a href='occasion.aspx' target='_self'>
            <img src='http://site.nl/643587726/image1.jpghttp://site.nl/643587727/image2.jpghttp://site.nl/643587728/image3' width='100%' border='0' height='100%' style='float: top; padding: 0px' />
        </a>
            <div id='textonadd'>

1 个答案:

答案 0 :(得分:0)

做这样的事情

$data = file_get_contents("vwe/autos.inc", "r") or die("Unable to open file!");
$images = array();
preg_match_all('/(img|src)=("|\')[^"\'>]+/i', $data, $media);
unset($data);
$data = preg_replace('/(img|src)("|\'|="|=\')(.*)/i', "$3", $media[0]);

foreach ($data as $url) {
    $info = pathinfo($url);
    if (isset($info['extension'])) {
        if (($info['extension'] == 'jpg') ||
            ($info['extension'] == 'jpeg') ||
            ($info['extension'] == 'gif') ||
            ($info['extension'] == 'png'))
            array_push($images, $url);
    }
}