PHP splits or explodes a string on an <img> tag

I would like to break a string into a tag into different parts.

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

The following function is not working correctly yet.

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

The exit should be

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

What model should I use to do this?

EDIT What if there are several 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.' ) 
+6
source share
2 answers

You are on the right track. You must set the flag PREG_SPLIT_DELIM_CAPTURE as follows:

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

With a few tags edited correctly, the regular expression:

 $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." } 
+2
source

You need to include an unwanted character ( ? ) In your template, as described here , to make it capture the first instance. '/(<img .*?\/>)/i'

so your sample code will look something like this:

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

What is the print result:

 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." } 
+1
source

Source: https://habr.com/ru/post/988841/


All Articles