2015-06-10 24 views
6

Vorrei dividere una stringa su un tag in parti diverse.PHP split o esplode stringa su <img> tag

$string = 'Text <img src="hello.png" /> other text.'; 

La funzione successiva non funziona ancora nel modo giusto.

$array = preg_split('/<img .*>/i', $string); 

L'uscita dovrebbe essere

array(
    0 => 'Text ', 
    1 => '<img src="hello.png" />', 
    3 => ' other text.' 
) 

Che tipo di modello devo usare per farlo fare?

MODIFICA Cosa succede se ci sono più tag?

$string = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.'; 
$array = preg_split('/(<img .*>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE); 

E l'uscita dovrebbe essere:

array (
    0 => 'Text ', 
    1 => '<img src="hello.png" />', 
    3 => 'hello ', 
    4 => '<img src="bye.png" />', 
    5 => ' other text.' 
) 

risposta

2

Sei in strada giusta. È necessario impostare il flag PREG_SPLIT_DELIM_CAPTURE in questo modo:

$array = preg_split('/(<img .*>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE); 

con tag multiple a cura adeguatamente l'espressione regolare:

$string = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.'; 
$array = preg_split('/(<img[^>]+\>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE); 

Questo stamperà:

array(5) { 
    [0]=> 
    string(5) "Text " 
    [1]=> 
    string(22) "<img src="hello.png" >" 
    [2]=> 
    string(7) " hello " 
    [3]=> 
    string(21) "<img src="bye.png" />" 
    [4]=> 
    string(12) " other text." 
} 
+0

È questo é piú attuale? Quando provo a echo questo codice vedo solo: 'array' – twan

+0

@twan, come hai usato? – Federkun

+0

L'ho già risolto, utilizzavo echo invece di print_r ($ array) lol. – twan

1

È necessario includere non personaggio avido (?) come descritto nello here nel proprio modello, per forzarlo ad afferrare il primo occorrente esempio. '/(<img .*?\/>)/i'

in modo che il codice di esempio sarà qualcosa del tipo:

$string = 'Text <img src="hello.png" /> hello <img src="bye.png" /> other text.'; 
$array = preg_split('/(<img .*?\/>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE); 

var_dump($array); 

che risultano alla stampa:

array(5) { 
    [0] => 
    string(5) "Text " 
    [1] => 
    string(23) "<img src="hello.png" />" 
    [2] => 
    string(7) " hello " 
    [3] => 
    string(21) "<img src="bye.png" />" 
    [4] => 
    string(12) " other text." 
}