PHP split or explode string on <img> tag
Asked Answered
E

2

8

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.'
)
Elvyn answered 10/6, 2015 at 10:49 Comment(0)
M
4

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."
}
Morganne answered 10/6, 2015 at 11:3 Comment(3)
Is this outdated? When I try to echo this code I only see: 'array'Velodrome
@twan, how did you used it?Morganne
I already fixed it, was using echo instead of print_r($array) lol.Velodrome
S
2

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."
}
Soapsuds answered 10/6, 2015 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.