PHP split or explode string on <img> tag

3k views Asked by At

i would like to split a string on a tag into different parts.

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

The next function doesnt work yet on the right way.

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

The output should be

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

What kind of pattern should i use to get it done?

EDIT What if there are multiple tags?

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

And the output should be:

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

There are 2 answers

3
Federkun On BEST ANSWER

You are in the right path. You have to set the flag PREG_SPLIT_DELIM_CAPTURE in this way:

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

With multiple tag edited properly the 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);

This will output:

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
Ali On

You need to include non-greedy character (?) as described here into your pattern as well, to force it to grab the first occurring instance. '/(<img .*?\/>)/i'

so your example code will be something like:

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

Which result to printing :

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