Question

My string follows the same character count pattern through each instance BUT some strings are longer or shorter so the solution would have to work for both long and short strings.

This is what I have:

XXXXXXX-​XXX-​XX|​XXXXXXX-​XXX-​XX|​XXXXXXX-​XXX-​XX|​XXXXXXX-​XXX-​XX|​XXXXXXX-​XXX-​XX|​XXXXXXX-​XXX-​XX

This is what I want to be left with:

XX|XX|XX|XX|XX

Where "XX" is the end of each section such as 0000000-000-XX

Was it helpful?

Solution

It's basically a combination of explode(), array_map() and join():

join('|', array_map(function($item) {
    return end((explode('-', $item)));
}, explode('|', $str)));

The inner explode() creates an array of all items between pipes from the given string, the array_map() takes the last piece of each dash delimited sub string and the final join() stitches them all together.

OTHER TIPS

First, initialize an output array to glue them together at the end.
First, would be to explode the string at point |.
Second, loop thru the exploded string (which is stored as array) then explode it again at point -. Lastly, get the last element of the array.

like:

$output = array() ; //initial output

foreach(explode('|', $item) as $items){ //explodes the string @ |
    foreach(explode($items) as $itm){ //explodes the string @ -
        $output[] = end($itm); //appends the last element in the array of output
    }
}

$output = implode('|', $output); //sticks the output together with |
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top