如何重写图像路径

时间:2010-12-17 19:32:25

标签: php jquery path rewrite

大家好,我正在寻求帮助重写图像路径。

让我解释.....

假设我正在运行2个应用程序。 APP-A和APP-B。我的APP-A安装了一个插件,它以纯HTML格式生成菜单的输出并保存为HTML文件。

我现在想将这个HTML文件导入我的APP = B并将其用作菜单。 HTML文件看起来像这样......

<div class="menu">
<li class="item27 parent root" >
    <a class="daddy item image subtext" href="/xyz/cms/index.php>
    <span>
        <img src="tmpl/abc_template/images/icons/icon.png" alt="icon1.png" />
        Link 1 <em>subline</em>
    </span>
    </a>
    </li>
    <li class="item27 parent root" >
    <a class="daddy item image subtext" href="/xyz/cms/index2.php>
        <span>
        <img src="tmpl/abc_template/images/icons/icon.png" alt="icon2.png" />
        Link 2 <em>subline</em>
        </span>
    </a>
    </li>
    <li class="item27 parent root" >
    <a class="daddy item image subtext" href="/xyz/cms/index3.php>
    <span>
        <img src="templ/abc_template/images/icons/icon.png" alt="icon3.png" />
        Link 3 <em>subline</em>
    </span>
    </a>
    </li>
</div>

我使用require_once('../../app-a/menu.html');

将此文件导入我的APP-B

文件正常,但我遇到图片路径问题。这些路径是相对于APP-A生成的,我想更改它们,以便我的APP-B从正确的位置获取它们。

例如,我在APP-B中导入文件后,

我希望我的APP-B在图像路径之前读取添加../../以便这些路径:

<img src="tmpl/abc_template/images/icons/icon.png" alt="icon1.png" />
<img src="tmpl/abc_template/images/icons/icon.png" alt="icon2.png" />
<img src="tmpl/abc_template/images/icons/icon.png" alt="icon3.png" />

变得像这些路径

<img src="../../tmpl/abc_template/images/icons/icon.png" alt="icon1.png" />
<img src="../../tmpl/abc_template/images/icons/icon.png" alt="icon2.png" />
<img src="../../tmpl/abc_template/images/icons/icon.png" alt="icon3.png" />

请帮助。我正在使用支持jQuery的模板。因此,即使是jQuery解决方案也可以。

3 个答案:

答案 0 :(得分:1)

可能最简单的方法就是在服务器上创建一个符号链接。

ln -s tmp1 ../../ tmp1

假设它是Linux / Apache服务器。或者您也可以在Apache配置中使用别名定义,或使用.htaccess执行相同的操作。

否则你必须开始乱砍HTML并动态重新创建它,我确信有几个库可以做到这一点,但可能有自己的警告和安全问题。

答案 1 :(得分:1)

如果你只是想要一个快速的解决方案,你可能会更成功地将菜单html文件读成一个字符串:

$menuString = file_get_contents('../../app-a/menu.html');

然后,您可以使用正则表达式将相对路径添加到每个src标记的开头。

preg_replace('%"tmpl/%is', '"../../tmpl/', $menuString);

这个正则表达式不是很强大,但它应该给你一个起点。

答案 2 :(得分:1)

嗯......我总是喜欢jQuery解决方案......

$(function() {
    $('.menu img').each(function() {
        img_path = $(this).attr('src');
        $(this).attr({'src': '../../' + img_path});
        });
    });

经过测试和工作。