1

假设有一个名为:

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

现在我想获取 url 部分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");
4

3 回答 3

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

于 2012-08-23T06:15:41.380 回答
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
        )

)

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

于 2012-08-23T06:52:29.090 回答
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");
}
于 2012-08-23T06:15:29.400 回答