Display Featured Links Randomly Using PHP
I had a request to add a "Link of the Day" feature to one of the pages on the Law-related Education pages of the OBA Web site using what we currently have in place. I’m sure there are widgets out there already that will do this for me, and it may even be built into whatever CMS we deploy next, but I wanted to learn a bit so I decided to implement it on our current site. I don’t know much about PHP, but I learned to code in VB.NET and C++, so I can learn enough as I go to make things work.
With the help of The Google, I was able to piece together a little bit of code that reads from a CSV file into an array, then randomly displays a link from within that array on each page load, so that a new link is loaded on each visit.
The original code has appeared in several forms across the Internet already, so if it’s yours, please let me know so I can credit you. I’ve made some slight adjustments to fit my needs.
1: <?php
2: function makeClickableLinks($text) {
3:
4: $text = eregi_replace('(((f|ht){1}(tp|tps)://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
5: '\\1', $text);
6: $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
7: '\\1\\2', $text);
8: $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
9: '\\1', $text);
10:
11: return $text;
12:
13: } // end function
14:
15:
16: function displayLink(){
17:
18: $fp = fopen("your-file.csv", "r");
19: while (!feof ($fp)) {
20: $contents[] = explode(",", fgets($fp, 512));
21: }
22: fclose ($fp);
23:
24: do {
25: $x = rand(0, count($contents)-1);
26: } while ($contents[$x] == '0');
27:
28: // displays link title above clickable URL
29: echo $contents[$x][0] . "<br />\n" . makeClickableLinks($contents[$x][1]) . "<br />\n";
30:
31: // displays link title as clickable link
32: echo '<a href="' . $contents[$x][1] . '" rel="nofollow">' . $contents[$x][0] . '</a>';
33:
34: } // end function
35:
36: ?>
37: <body>
38: <?php displayLink(); ?>
39: </body>
Click to view a working sample of this page here.
WordPress Tags: Display,Links,Link,Education,code,Google,Internet,text,Click,Development,adjustments,makeClickableLinks,eregi_replace,displayLink,clickable
My CodeProject articles
Read Full Post | Make a Comment ( 1 so far )


