I have a string like following
Overall Queen Poster <br /> Queen Poster Headboard:<br /> Queen Poster <br /> Queen Footboard <br /> Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs.
How to explode it on
tag so that I can get the values in an array?
I tried this
$myString = "Overall Queen Poster <br /> Queen Poster Headboard:<br /> Queen Poster <br /> Queen Footboard <br /> Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs";
$myArray = explode("\n",$myString);
print_r($myArray);
But not getting correct result.
That's because <br />
!= \n
.
You can use regex to split it, to make sure that you get all the BR tags (<br>
, <br />
, <br/>
, <br class="break">
, <BR>
etc.)
Code:
<?php
$myString = 'Overall Queen Poster <br /> Queen Poster Headboard:<br /> Queen Poster <br /> Queen Footboard <br /> Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs.';
$myArray = preg_split('/<br[^>]*>/i', $myString);
print_r($myArray);
?>
Outputs:
Array
(
[0] => Overall Queen Poster
[1] => Queen Poster Headboard:
[2] => Queen Poster
[3] => Queen Footboard
[4] => Queen Poster Rails: 62.28"W x 84.02"D x 18.07"H - 37lbs.
)
DEMO
Limitations:
Will split on any HTML tags that start with br
. Meaning that if you made your own tag, such as <breadcrumb>
, this would mistakenly be seen as a line break.
Alternatives:
explode('<br />', $myString)
if you're sure that your tags will always be exactly <br />
preg_split('/<br\s*/?>/i', $myString)
if you have tags such as <breadcrumb>
and don't have any attributes in any <br>
tag.Extra notes:
If you don't want white-space in your matches, you can change your regex to /<br[^>]*>\s*/i
which will also match any white-space characters after the match. Alternatively, you can run it through ltrim
with $myArray = array_map('ltrim', $myArray);
.
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