I've sear开发者_JS百科ched long and hard for an answer to doing this & have come up with nothing. I know someone here will have an answer.
First, I get the URL and grab the subsite out of the beginning:
<?php
// get page URL
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
// get host name from URL
$url = preg_replace('(https?://)', '', $pageURL);
$affUrl = explode('.', $url);
$aff = $affUrl[0];
?>
If the URL is affiliate1.domain.com
, this returns affiliate1
as $aff
.
Next, I have affiliates.txt
each with a different name on each line:
affiliate1
affiliate2
affiliate-3 (yes, this is correct)
Then, I read that file into an array:
<?php
// read affiliates.txt and create array
$affs = file("affiliates.txt");
// search for affiliate in array
$inarray = array_search($aff, $affs); // i've tried in_array() also
if ($inarray !== false) echo '<img src="affiliatelogos/$aff.jpg" class="aff-img" alt="$aff" />';
?>
However, even when I hardcode an affiliate name into array_search()
:
$inarray = array_search('affiliate1', $affs);
It returns nothing. What am I doing wrong here?
Each line includes a newline character, you can ignore them by providing a flag to the "file" function:
$affs = file('affiliates.txt', FILE_IGNORE_NEW_LINES);
Try trimming all the values in the array to remove trailing whitespace and new line characters. This is the simplest way of doing it:
array_walk($affs, create_function('&$val', '$val = trim($val);'));
精彩评论