简体   繁体   中英

preg_grep(): Compilation failed: nothing to repeat at offset 0

After updating my PHP from 5.3 to 7.1.9, I keep getting this error on my get_browser_language function.

I tried to debug it using several method but no luck, the variables etc all are correct.

Code;

function get_browser_language( ) {
    global $cachedb;
    $available = array();
    $default = get_option('def_lang','tr');
    // List available
    $avails = $cachedb->get_results( "SELECT `lang_code` FROM  ".DB_PREFIX."languages");
    foreach ($avails as $av){
    $available[] = $av->lang_code;     
    }
    if ( isset( $_SERVER[ 'HTTP_ACCEPT_LANGUAGE' ] ) ) {
        $langs = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
    if ( empty( $available ) ) {
      return $default;
    }
        foreach ( $langs as $lang ){
            $lang = substr( $lang, 0, 2 );
            if( in_array( $lang, $available ) ) {
                return $lang;
            }
            //Test for XX-nr
            $matches = preg_grep('/'.$lang.'/', $available);
            if($matches) { 
            if(isset($matches[0])) {            
            return $matches[0];
            }
            }
        }
    }
    return $default;
}

I keep getting warning at $matches = preg_grep('/'.$lang.'/', $available);

Warning;

PHP Warning:  preg_grep(): Compilation failed: nothing to repeat at offset 0 ...

What could be the issue? Thanks in advance!

@Toto gave me an idea with his comment. After spending some time on checking $_SERVER['HTTP_ACCEPT_LANGUAGE'] values, it returns empty value sometimes and I believe this was the reason I'm receiving this warning.

So basically I did the following;

I changed

//Test for XX-nr
$matches = preg_grep('/'.$lang.'/', $available);

to this;

//Test for XX-nr
if(ctype_alnum($lang)){
    $matches = preg_grep('/'.$lang.'/', $available);
    //error_log(print_r("LANG: " . $lang, TRUE));
}

So it returns default lang-code when $_SERVER['HTTP_ACCEPT_LANGUAGE'] returns empty result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM