2015-06-10 51 views
6

Chciałbym podzielić ciąg na tag na różne części.PHP split lub explode string na <img> tag

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

Następna funkcja nie działa jeszcze we właściwy sposób.

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

Wyjście powinno być

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

Jaki wzór należy użyć, aby to zrobić?

EDYTOWANIE Co zrobić, jeśli jest wiele tagów?

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

a wyjście powinno być:

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

Odpowiedz

2

Jesteś na właściwej drodze. Trzeba ustawić flagę PREG_SPLIT_DELIM_CAPTURE w ten sposób:

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

z wieloma tagu redakcją prawidłowo regex:

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

Wyjście to będzie:

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

Czy to nieaktualne? Kiedy próbuję odtworzyć ten kod, widzę tylko: 'array' – twan

+0

@twan, jak go użyłeś? – Federkun

+0

Już to naprawiłem, korzystałem z echa zamiast z print_r ($ array) lol. – twan

1

Trzeba to nie- chciwy charakter (?) zgodnie z opisem w here na swój wzór, aby zmusić go do uchwycenia pierwszego wystąpienia instancja. '/(<img .*?\/>)/i'

więc przykładowy kod będzie coś takiego:

$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); 

które wynikają z drukowaniem:

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." 
}