2010-08-07 13 views

risposta

71

E.g. via array_filter() o utilizzando l'opzione PREG_SPLIT_NO_EMPTY su preg_split()

<?php 
// only for testing purposes ... 
$_POST['tag'] = ",jay,john,,,bill,glenn,,0,,"; 

echo "--- version 1: array_filter ----\n"; 
// note that this also filters "0" out, since (bool)"0" is FALSE in php 
// array_filter() called with only one parameter tests each element as a boolean value 
// see http://docs.php.net/language.types.type-juggling 
$tags = array_filter(explode(",", $_POST['tag'])); 
var_dump($tags); 

echo "--- version 2: array_filter/strlen ----\n"; 
// this one keeps the "0" element 
// array_filter() calls strlen() for each element of the array and tests the result as a boolean value 
$tags = array_filter(explode(",", $_POST['tag']), 'strlen'); 
var_dump($tags); 

echo "--- version 3: PREG_SPLIT_NO_EMPTY ----\n"; 
$tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY); 
var_dump($tags); 

stampe

--- version 1: array_filter ---- 
array(4) { 
    [1]=> 
    string(3) "jay" 
    [2]=> 
    string(4) "john" 
    [5]=> 
    string(4) "bill" 
    [6]=> 
    string(5) "glenn" 
} 
--- version 2: array_filter/strlen ---- 
array(5) { 
    [1]=> 
    string(3) "jay" 
    [2]=> 
    string(4) "john" 
    [5]=> 
    string(4) "bill" 
    [6]=> 
    string(5) "glenn" 
    [8]=> 
    string(1) "0" 
} 
--- version 3: PREG_SPLIT_NO_EMPTY ---- 
array(5) { 
    [0]=> 
    string(3) "jay" 
    [1]=> 
    string(4) "john" 
    [2]=> 
    string(4) "bill" 
    [3]=> 
    string(5) "glenn" 
    [4]=> 
    string(1) "0" 
} 
+0

+1 modo perfetto per farlo mentre i mis-leggere la domanda :) – Sarfraz

+0

ha non funziona a tutti :( – snag

+0

@snag: funziona. – Sarfraz

0
//replace multiple commas 
$tags = preg_replace('/,+/', ',', $_POST['tag']); 
//explode 
$tags = explode(',', $tags); 
+0

non ha funzionato affatto :( – snag

+0

sei sicuro che le virgole non sono codificate come entità? – Haroldo

+0

Dovrebbe essere 'explode (',', $ tags) 'e mantiene l'ultimo elemento vuoto per la stringa data' ", jay, john ,,, bill, glenn ,,,". – VolkerK

0
$tags = array_diff(explode(",", $_POST['tag']),array("")); 
Problemi correlati