Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Display a random link from a CSV
<?php
include_once 'links.php';
display_link('links.csv');
<?php
/**
* Reads in a CSV file and displays a random link.
*
* @version 2.0.0
* @author Morgan Estes <morgan.estes@gmail.com>
* @license GPLv3
*/
/**
* Use regex to parse the strings provided
*
* @deprecated eregi_replace replaced by preg_replace in PHP5
* @param string $text
*
* @return string
*/
function makeClickableLinks( $text ) {
$text = eregi_replace( '(((f|ht){1}(tp|tps)://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1', $text );
$text = eregi_replace( '([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1\\2', $text );
$text = eregi_replace( '([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '\\1', $text );
return $text;
}
/**
* Use regex to parse a string to make it a hyperlink
*
* @param string $text the text to turn into a hyperlink
* @return string a hyperlinked version of $text
*/
function make_clickable_links( $text ) {
$text = preg_replace( '/(((f|ht){1}tp:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
'<a href="\\1">\\1</a>', $text );
$text = preg_replace( '/([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
'\\1<a href="http://\\2">\\2</a>', $text );
$text = preg_replace( '/([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i',
'<a href="mailto:\\1">\\1</a>', $text );
return $text;
}
/**
* Get file contents, run through a randomizer, and display on the screen
*
* @param string $csv path to file
* @param string $display inline or above
* @return string link with text
*/
function display_link( $csv, $display = 'inline' ) {
$fp = fopen( $csv, "r" );
while ( !feof( $fp ) ) {
$contents[] = explode( ",", fgets( $fp, 512 ) );
}
fclose( $fp );
do {
$x = rand( 0, count( $contents ) - 1 );
} while ( $contents[$x] == '0' );
$link = $contents[$x][1];
$text = $contents[$x][0];
if ( $display == 'above' ) {
// displays link title above clickable URL
echo "<span>$link<br>" . make_clickable_links( $link );
} else {
// displays link title as clickable link
echo "<a href='$link' rel='nofollow'>$text</a>";
}
}
@papush

This comment has been minimized.

Copy link

commented Aug 26, 2017

Hi, i'm just starting to learn about code so pardon my ignorance.
Is this possible with embeds instead of links ? I'm really interested in using such a function but with embedded videos from youtube, and potentially other types of embeds too
thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.