<?php
## filename: [/LIB-DIR/]ftx_format_german.php

/*
Die benötigte Datei vorwahlen.extended.inc.php können Sie mit diesem Stuff erzeugen:
http://www.fastix.org/r/vorwahlen_files_generate.php.html

Includieren, Aufruf mit ftx_format_german_tel($TelefonNummer);

Lizenz: LGPL
Rechte: Jörg Reinholz, http://www.fastix.org, joerg.reinholz@fastix.org

Gerne leiste ich in Ihrem Auftrag Folgendes:
- Anpassung, Integration
- Erweiterung auf andere Länder
*/


require ('vorwahlen.extended.inc.php'); #liefert $ar_vw_parts_ort
global $ar_vw_parts_ort;


# Test bei Direktaufruf
if ( -1 < strpos($_SERVER['PHP_SELF'],'ftx_format_german.php')) {
   
ftx_format_german_test();
}


function 
ftx_format_german_test() {
    
$telefonnummern = array(
        
'456789',
        
'45 67 89',
        
'089 456789',
        
'0371 45 67 89',
        
'039856-45 67 89',
        
'0049 (0) 89 456789',
        
'0049 (0) 371 45 67 89',
        
'0049 (0) 39856-45 67 89',
        
'+49 89 456789',
        
'+49 371 45 67 89',
        
'+49 39856-45 67 89',
        
'+33 2 123 123 123 123'
    
);
    foreach (
$telefonnummern as $t) {
        echo 
"\nOriginal: $t", "\nGeklärt:  ", ftx_format_german_tel($t), "\n";
    }
}

function 
ftx_format_german_tel($t) {
    
$german_tel = false;
    
$has_0049   = false;
    
$has_vw     = false;
    
$err        = true;

    
$t=preg_replace( '/^\+{1,2}/', '00', trim($t) );
    
$t=preg_replace( '/^00/', '+', trim($t) );
    
$t=str_replace( '(0)', '', $t );
    
$t=preg_replace('/[^\d+]/', '', $t);

    if ( 
preg_match('/^\+49/', $t) )   { $german_tel = true; $has_0049 = true; $t=substr($t, 3, 99); }
    if ( 
preg_match('/^0[1-9]/', $t) ) { $german_tel = true; $has_vw   = true; $t=substr($t, 1, 99); }

    if ( !
$has_0049 && !$has_vw ) {
       return 
group_tel($t, 3);
    }


    
$ar_t=str_split($t,1);
    
$tmp_vw  = '';
    
#$tmp_num = '';
    
$ar_vw_parts_ort = $GLOBALS['ar_vw_parts_ort'];
    if ( ! empty(
$ar_vw_parts_ort[0])) {
        
$ar_vw_rest = $ar_vw_parts_ort[0];
    } else {
        
$ar_vw_rest = $ar_vw_parts_ort;
    }

    while ( 
$c = array_shift($ar_t) or $c === '0') {
        if ( ! empty(
$ar_vw_rest[$c]) ) {
            
$ar_vw_rest = $ar_vw_rest[$c];
            
$tmp_vw .= $c;
        }
        if ( ! empty(
$ar_vw_rest["txt"]) ) {
            
$tmp_num = group_tel(implode('', $ar_t));
            
$ar_t=array();
        }
    }

    if (
$has_0049) { return "+49-$tmp_vw-$tmp_num"; };
    if (
$has_vw)   { return "+49-$tmp_vw-$tmp_num"; };
}

function 
group_tel($t, $n=3) {
   return 
implode(' ', str_split($t,$n) );
}