Das geht auch ohne Regex:
<?php
## file: SelectOneOffAcceptedLanguages.php
function SelectOneOffAcceptedLanguages ( $arList, $showDebug = 0) {
## accept a array of languages (strings) (e.g. array('de', 'en-US', 'en', 'fr')) as first argument
## returns, if in $arList, the accepted language with the highest quota from $_SERVER['HTTP_ACCEPT_LANGUAGE']
## if not a accepted language in $arList, return the fist Element in $arList
## if debug set this will echo debug-informations
## show ISO 639-1 and RFC 1766 for more Informations
## rfc2616 section 14 for the HTTP_ACCEPT_LANGUAGE-Header
$arTmp = array();
foreach ($arList as $s) {
$s=trim($s);
if ($s) {
$arTmp[] = strtolower($s);
}
}
$arList = $arTmp;
$arAcceptedLanguages = array();
$arTmp = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($arTmp as $item) {
$arLangQuote = array();
$arLangQuote = explode(';', $item);
if (! isset($arLangQuote[1]) ) {
$arLangQuote[1] = 1;
}
$arLangQuote[0] = trim( $arLangQuote[0] );
if ( $arLangQuote[0] ) {
$arT['quote'] = floatval( trim( str_replace( 'q=', '', $arLangQuote[1] ) ) );
$arT['lang'] = strtolower($arLangQuote[0]);
$arAcceptedLanguages[] = $arT;
}
}
if ($showDebug) { print_r($arAcceptedLanguages); }
$retLang = $arList[0];
$SelectedLanguage = $arList[0];
$quote = 0;
foreach ( $arList as $lang ) {
$lang = trim( $lang );
foreach ($arAcceptedLanguages as $arTmp) {
if ($showDebug) { echo "Test: $lang == " . $arTmp['lang'] . ' && ' . $arTmp['quote'] . " > $quote\n"; }
if ( $lang == $arTmp['lang'] && $arTmp['quote'] > $quote ) {
$retLang = $arTmp['lang'];
$quote = $arTmp['quote'];
if ($showDebug) { echo "Winner is: " . $arTmp['lang'] . "( Quote: " . $arTmp['quote'] . ")\n"; }
}
}
}
return $retLang;
}
#/* Test ( To disable the test remove the first '#' in this line. On production systems delete all the stuff downside this line)
## Values to edit:
## Present Languages, comma-separated, try with errors (lower, upper, spaces):
$list="fr, en, es";
$showDebug = true;
# Overwrite
## Simulate the HTTP_ACCEPT_LANGUAGE - header, try with errors (lower, upper, spaces):
$HttpAcceptLanguage="de-DE,de ;q=0.8, en-US;q=0.5,en;q=0.3";
#$HttpAcceptLanguage=false;
if ($HttpAcceptLanguage) {
$_SERVER['HTTP_ACCEPT_LANGUAGE']=$HttpAcceptLanguage;
}
if (! isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
echo "\n\nTest: Settings Error: You have not set a \$HttpAcceptLanguage and \$_SERVER knows nothing about this... - Nothing to test. Exit!\n\n";
exit;
}
##Program:
header('Content-Type: text/plain');
echo "\n\nTest of " . __FILE__ . "\n Accepted: " . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . "\n Present: $list\nselected: " . SelectOneOffAcceptedLanguages( explode( ',', $list), $showDebug ) . "\n\n";
# */
Ich hoffe ja, dass der Beitrag nicht von @1unitedpower mit der Begründung gelöscht wird, dass die "Sicherheit nicht nachgewiesen" sei und weil @1unitedpower a) nicht durchsieht und b) nicht mit automatisierten Tests darauf ballern kann.