Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中修复回显链接url数组?_Php - Fatal编程技术网

如何在php中修复回显链接url数组?

如何在php中修复回显链接url数组?,php,Php,我有一个代码示例: include 'simple_html_dom.php'; // convert link url function foo($uri) { $url = parse_url($uri); $paths = explode('/', $url['path']); return sprintf("%s://%s/%s", $url['scheme'], 'localhost/test/get_image/imag

我有一个代码示例:

include 'simple_html_dom.php';
    // convert link url
    function foo($uri) {
        $url = parse_url($uri);
        $paths = explode('/', $url['path']);
        return sprintf("%s://%s/%s", $url['scheme'], 'localhost/test/get_image/images', end($paths));
    }
    $str = '<img src="http://www.somedomain.com/somepic.jpg" />
    <img src="http://www.microsoft.com/somepic.jpg" />';
    $html = new simple_html_dom();
    $html->load($str);
    // remove all image
    $arr_img = array();
    foreach($html->find('img') as $element) {
        $arr_img[] = $element->src;
    $str_rep = str_replace($element->src, foo($element->src), $str);
    }
    echo $str_rep;
包括“simple_html_dom.php”;
//转换链接url
函数foo($uri){
$url=parse_url($uri);
$path=explode('/',$url['path']);
返回sprintf(“%s://%s/%s”、$url['scheme']、'localhost/test/get_image/images',end($path));
}
$str='1
';
$html=新的简单html\U dom();
$html->load($str);
//删除所有图像
$arr_img=array();
foreach($html->find('img')作为$element){
$arr_img[]=$element->src;
$str_rep=str_replace($element->src,foo($element->src),$str);
}
echo$str_rep;
输出:


无法获取链接时出错“http://www.somedomain.com/somepic.jpg“不转换为”http://localhost/test/get_image/images/somepic.jpg"
如何修复它?

您正在为foreach循环中的
$str_rep
赋值,但使用了它之外的变量:您只处理最后一个匹配

请尝试以下方法:

foreach($html->find('img') as $element) {
    $arr_img[] = $element->src;
    $str_rep = str_replace($element->src, foo($element->src), $str);
    echo $str_rep;
}
结果是:测试
foreach($html->find('img') as $element) {
    $arr_img[] = $element->src;
    $str_rep = str_replace($element->src, foo($element->src), $str);
    echo $str_rep;
}