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.'
)
Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
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."
}
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."
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With