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

有帮助吗?

解决方案

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.

其他提示

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 |
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top