FreshPro FreshPro - 7 months ago 16
PHP Question

php parse string and copy elements

Let's say, I have a dynamic string like this:

$string = "ABC-DEF-GHI-JKL";


or this

$string = "ABC-DEF-GHI";


string is changable

what I want to do is to parse string, duplicate all elements besides first one and last one like this:

ABC-DEF
DEF-GHI
GHI-JKL


or like this

ABC-DEF
DEF-GHI


What should be the logic here? How can I achieve that?

PS: I know I can use

explode("-", $string);


which gives me an array like this:

[0]->ABC
[1]->DEF
[2]->GHI
[3]->JKL


But I don't know how to foreach this string. Any help is appriciated.

Answer

Here you go:

<?php

$string = "ABC-DEF-GHI-JKL";

$parts = explode("-", $string);

for ($i = 0; $i < count($parts) - 1; $i ++) {
        echo $parts[$i] . '-' . $parts[$i + 1] . "\n";
}