简体   繁体   中英

Split a string with <span> using preg_split()

I have a sting that is in this format.

<span class="amount">$25</span>–<span class="amount">$100</span>

What I need to do is split that into two strings. The string will remain in the same format but the prices will change. I tried using str_split() but because the price changes I wouldn't be able to always know how many characters to split the string at.

What I am trying to get is something like this.

String 1

<span class="amount">$25</span>–

String 2

<span class="amount">$100</span>

It seems the best option I have found is to use preg_split() but I don't know anything about regex so I'm not sure how to format the expression. There may also be a better way to handle this and I just don't know of it.

Could someone please help me format the regex, or let me know of a better way to split that string.

Edit

Thanks to @rm-vanda for helping me figure out that I don't need to use preg_split for this. I was able to split the string using explode(). The issue I was having was because the '-' was encoded weird and therefore not returning correctly.

It might be better to translate this problem into DOM:

$html = <<<HTML
<span class="amount">$25</span>–<span class="amount">$100</span>
HTML;

$doc = new DOMDocument;
$doc->loadHTML($html);

foreach ($doc->getElementsByTagName('span') as $span) {
    // do stuff with $span
    // e.g. this is how you would get the outer html
    echo $doc->saveXML($span);
}

If it always has the "-" then this would be the most simple way:

$span = explode("-", $spans); 

echo $span[0]; 

echo $span[1]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM