【问题标题】:Changing relative to absolute links contained in a string相对于字符串中包含的绝对链接进行更改
【发布时间】:2013-07-15 18:42:02
【问题描述】:

我有 PHP 变量保存字符串,在里面我混合了包含链接和其他包含图像链接的内容,如下所示

$baseurl = "http://www.myweb.com/home/";
$content = "<a href="#"><img src="images/comment.gif" alt="Comment" /></a></p>
           <div class="thirds"> <p><b><a  href="admin/local.html" class="title">Manage your content</a></b><br /><img src ="subfolder/home.jpg" alt="home" />Lorem ipsum dolor sit amet esta pa, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt....";

我的目标是回显变量“内容”,其中所有链接都带有标记,src 标记,修改为绝对含义,因为包含的第一个 $content 链接必须是 &lt;a href="http://www.myweb.com/home/#" 这应该与所有图像示例相同&lt;img src="images/comment.gif 应该是 &lt;img src="http://www.myweb.com/home/images/comment.gif alt="Comment" /&gt;.. 任何帮助,请注意,所有内容都包含在一个 php 字符串变量中。

【问题讨论】:

  • 使用正则匹配字符串,检查href="后面是否有$baseurl变量的内容(本例为http://www.myweb.com/home/),如果没有,插入即可。

标签: php javascript jquery dom


【解决方案1】:

你有两种方法:

  1. 服务器端,通过php,用正则表达式替换字符串(我不知道)。

  2. 浏览器端,通过 jquery:

    var baseurl = "http://www.myweb.com/home/";
    $("#container [src]").prop("src",function(index,oldValue){
        return baseurl+oldValue;
    });
    
    $("#container [href]").prop("href",function(index,oldValue){
        return baseurl+oldValue;
    });
    

将更多属性放入数组中并在 for 循环中执行它们很容易。

"container" 是包含您的内容的 dom 元素的 id。是这样的:

<div id="container">
   <a href="#"><img src="images/comment.gif" alt="Comment" /></a></p>
       <div class="thirds"> <p><b><a  href="admin/local.html" class="title">Manage your content</a></b><br /><img src ="subfolder/home.jpg" alt="home" />Lorem ipsum dolor s...
</div> 

【讨论】:

    【解决方案2】:

    试试这个(快速而肮脏的方式,但可能比正则表达式更快):

    str_replace("href=\"", "href=\"".$baseurl, $content);
    str_replace("href=\'", "href=\'".$baseurl, $content);
    str_replace("src=\"", "src=\"".$baseurl, $content);
    str_replace("src=\'", "src=\'".$baseurl, $content);
    

    【讨论】:

    • 以上假设 $content var 中的所有链接出现都是相对的,必须替换
    【解决方案3】:

    您可以将 $baseurl 添加到 src。 还将“更改为”,以便您可以在字符串中使用“。或者如果你使用heredoc更好。

    $baseurl = "http://www.myweb.com/home/";
    $content = '<a href="'. $baseurl . '#"><img src="'. $baseurl . 'images/comment.gif" alt="Comment" /></a></p>
           <div class="thirds"> <p><b><a  href="admin/local.html" class="title">Manage your content</a></b><br /><img src ="'. $baseurl . 'subfolder/home.jpg" alt="home" />Lorem ipsum dolor sit amet esta pa, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt....';
    

    【讨论】:

    • $content 不是静态的,根据被获取并存储在 $content 变量中的数据是动态的,是否有任何函数可以检查所有 $content 字符串,检测链接或图像并更改其相对链接到绝对取决于 $baseurl?
    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2011-04-19
    • 1970-01-01
    • 2010-10-09
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多