我有一个查询。我想自动添加一个PHP代码到页面上每个链接的末尾。例如,如果我在页面上有100个html链接,例如:
<a href="http://example.com/" class="example">
我想自动将其更改为:
<a href="http://example.com/<?php echo $ref; ?> class="example">
对于我页面上的每个链接,我最好如何实现它?不幸的是,不能简单地将php代码添加到我页面上的每个链接。我只看到一篇与谷歌有关的帖子没有帮助。
答案 0 :(得分:1)
如果插入PHP代码是一次性任务,您可以使用&#34;替换文本&#34;编辑的功能。 您可以让它替换每次出现的
<a href="http://example.com/" class
通过
<a href="http://example.com/<?php ... ?>" class
例如,看看Geany:https://askubuntu.com/questions/302914/find-and-replace-text-in-multiple-files-using-geany
如果您经常或自动执行此操作,您可以使用例如php的preg_replace函数来处理输入的HTML文件。
答案 1 :(得分:1)
Javascript可以帮助您实现这一目标。
function renameLinks(){
var myList = document.getElementsByTagName("a");
for (var i =0;i<myList.length;i++){
myList[i].setAttribute('href', 'http://example.com/<?php echo $ref; ?>');
}
}
创建一个以URL作为参数的函数,它将生成您的链接:
function createLink(url){
var newLink = document.createElement('a');
newLink.href = 'url'+'<?php echo $ref; ?>';
return newLink;
}
答案 2 :(得分:1)
sed -i 's/<a href="http:\/\/example\.com\/"/<a href="http:\/\/example\.com\/<\?php echo $ref; \?>"/g' *.php
在终端中运行它,它将替换所有
<a href="http://example.com/"
与
<a href="http://example.com/<?php echo $ref; ?>"
在当前目录的所有* .php文件中。
更新:
sed -i 's/old/new/g'
sed
=流编辑评论-i
=替换原始文件s
=替代命令old
=描述要替换的单词的正则表达式new
=用g
=替换所有事件*.php
=通配符文件名答案 3 :(得分:0)
<强>建议:强>
由于您必须修改所有代码,
为什么不删除http://example.com/
?
使用vim,您可以使用
%s/http:\/\/example.com\/<?php echo $domain . $ref;?>
您需要定义$domain
或使用常量:
define("MYDOMAIN", "http://example.com/");
php echo MYDOMAIN . $ref;
然后在vim中替换(作为替换)将是
%s/http:\/\/example.com\/<?php echo MYDOMAIN . $ref;?>