2012-04-11 28 views
31

Ho bisogno di un modo per catturare il testo tra parentesi quadre. Così, per esempio, la seguente stringa:Catturare il testo tra parentesi quadre in PHP

[This] is a [test] string, [eat] my [shorts].

Potrebbe essere utilizzato per creare la seguente matrice:

Array ( 
    [0] => [This] 
    [1] => [test] 
    [2] => [eat] 
    [3] => [shorts] 
) 

Ho la seguente espressione regolare, /\[.*?\]/ ma coglie solo la prima istanza, in modo da:

Array ([0] => [This]) 

Come posso ottenere l'uscita di cui ho bisogno? Nota che le parentesi quadre non sono MAI annidate, quindi non è un problema.

+0

+1 Grazie! Questo è stato. –

+0

Voto positivo per "mangia i miei pantaloncini", applausi a un fan dei Simpson. –

risposta

72

Partite tutte le stringhe con le staffe:

$text = '[This] is a [test] string, [eat] my [shorts].'; 
preg_match_all("/\[[^\]]*\]/", $text, $matches); 
var_dump($matches[0]); 

Se si desidera stringhe senza parentesi:

$text = '[This] is a [test] string, [eat] my [shorts].'; 
preg_match_all("/\[([^\]]*)\]/", $text, $matches); 
var_dump($matches[1]); 

alternativi, versione più lenta di corrispondenza senza parentesi (usando "*" invece di "[^] "):

$text = '[This] is a [test] string, [eat] my [shorts].'; 
preg_match_all("/\[(.*?)\]/", $text, $matches); 
var_dump($matches[1]); 
+8

E se vuoi le stringhe tra parentesi: preg_match_all ("/\[(.*?)\]/",$ text, $ matches); –

+3

@GertVandeVen: barre rovesciate richieste. preg_match_all ("/\\[(.*?)\\]/",$ text, $ matches). Probabilmente il web ha rimosso il tuo;) – Naki

+0

@GertVandeVen Stranamente, ora ho il seguente: 'Array ([0] => Array ([0] => [This] [1] => [test] [2] => [eat ] [3] => [shorts]) [1] => Array ([0] => This [1] => test [2] => eat [3] => shorts)) ' –

Problemi correlati