如何在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;
}