如何获取网址并将它们放在一行一行的文本文件中?

时间:2012-08-23 06:08:28

标签: php

假设有一个名为:

的变量
src="http://www.test.com/1455/"||src="http://www.test.com/image/1456/"||

现在我想获取网址http://www.test.com/1455/

以下是我的代码。但它不起作用。

$url = 'src="http://www.test.com/1455/"||src="http://www.test.com/image/1456/"||';

$a = explode("src=\"",$url); 
$b = explode("||",$a); 
$handle = fopen("output.txt", 'a')) !== FALSE
fwrite($handle2, "{$b[0]}\n");

3 个答案:

答案 0 :(得分:1)

使用类似于此的正则表达式,当然您可以根据需要修改它。这只是一个例子,但它适用于你

$url = 'src="http://www.test.com/1455/"||src="http://www.test.com/image/1456/"||';
preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i', $url, $result, PREG_PATTERN_ORDER);
print_R($result);

它会打印

Array
(
    [0] => Array
        (
            [0] => http://www.test.com/1455/
            [1] => http://www.test.com/image/1456/
        )

)

并将其写入文本文件:

$handle = fopen("output.txt", 'a');
foreach($result[0] as $url){
    fwrite($handle, $url."\n");     
}
fclose($handle);

有关正则表达式的详细信息http://php.net/manual/en/function.preg-match.php

答案 1 :(得分:1)

解决更一般的情况。此代码将您的字符串转换为URL查询格式,并通过parse_str函数

进行解析
$url = 'src="http://www.test.com/1455/"||src="http://www.test.com/image/1456/"||var1=aaa||var2=bbb||var2=bbb';
$url = str_replace('||', '&', $url);
$url = preg_replace('/([^\]])=/', '$1[]=', $url);

$params = array();
parse_str($url, $params);

print_r($params);

输出:

Array
(
    [src] => Array
        (
            [0] => "http://www.test.com/1455/"
            [1] => "http://www.test.com/image/1456/"
        )

    [var1] => Array
        (
            [0] => aaa
        )

    [var2] => Array
        (
            [0] => bbb
            [1] => bbb
        )

)

然后你可以用这个数组做你想要的一切

答案 2 :(得分:0)

$url = 'src="http://www.test.com/1455/"||src="http://www.test.com/image/1456/"||';

$a = explode("||",$url); 

$handle = fopen("output.txt", 'a');
foreach($a as &$val)
{
   $val = str_replace("src=\"","",$val);
   $val  = str_replace("\"","",$val);
   fwrite($handle, "{$val}\r\n");
}