我有一个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....";
我的目标是回显变量"content",其中所有链接都带有一个标记src标记,修改为绝对意义,因为包含的第一个$content链接必须是<a href="http://www.myweb.com/home/#"
,这应该与所有图像相同,例如<img src="images/comment.gif
应该是<img src="http://www.myweb.com/home/images/comment.gif alt="Comment" />
。。任何帮助,请注意,所有内容都包含在php字符串变量中。
您可以将$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....';
试试这个(快速而肮脏的方法,但可能比regexp更快):
str_replace("href='"", "href='"".$baseurl, $content);
str_replace("href=''", "href=''".$baseurl, $content);
str_replace("src='"", "src='"".$baseurl, $content);
str_replace("src=''", "src=''".$baseurl, $content);
您有两种方法:
-
服务器端,通过php,用正则表达式替换字符串(我不知道)。
-
浏览器端,通过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>