Reputation: 565
I have a query. I want to add a php code automatically to the end of every link on a page. For example, if I have 100 html links on a page for example:
<a href="http://example.com/" class="example">
and I wanted to automatically change this to:
<a href="http://example.com/<?php echo $ref; ?> class="example">
for every link on my page, how would I best implement it? Unfortunately, it is not an option to simply add the php code to every single link on my page. I've seen only one post related to this from Google that did not help.
Upvotes: 0
Views: 417
Reputation: 8222
sed -i 's/<a href="http:\/\/example\.com\/"/<a href="http:\/\/example\.com\/<\?php echo $ref; \?>"/g' *.php
Run this in terminal, it will replace all
<a href="http://example.com/"
with
<a href="http://example.com/<?php echo $ref; ?>"
in all the *.php files of current directory.
Update:
sed -i 's/old/new/g'
sed
= Stream editor comment-i
= replace original files
= the substitute commandold
= a regular expression describing the word to replacenew
= the text to replace it withg
= replace all occurrence*.php
= wildcard file nameUpvotes: 1
Reputation: 811
Javascript can help you doing this.
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; ?>');
}
}
Create a function which takes a URL as parameter and it will generate your link:
function createLink(url){
var newLink = document.createElement('a');
newLink.href = 'url'+'<?php echo $ref; ?>';
return newLink;
}
Upvotes: 1
Reputation: 17324
Suggestion:
Since you have to modify all your code,
why not remove the hard-coding of http://example.com/
?
With vim, you could use
%s/http:\/\/example.com\/<?php echo $domain . $ref;?>
you need to define $domain
or use a constant:
define("MYDOMAIN", "http://example.com/");
php echo MYDOMAIN . $ref;
Then the replace (s as substitution) in vim would be
%s/http:\/\/example.com\/<?php echo MYDOMAIN . $ref;?>
Upvotes: 0
Reputation: 1183
If the inserting of the PHP code is a one-time task, you could use a "replace text" function of your editor. You could have it replace each occurrence of
<a href="http://example.com/" class
by
<a href="http://example.com/<?php ... ?>" class
For example, have a look at Geany: https://askubuntu.com/questions/302914/find-and-replace-text-in-multiple-files-using-geany
If you have to do this often or automatically, you could use, for example, the preg_replace functions of php to process your input HTML files.
Upvotes: 1