FreshPro FreshPro - 1 year ago 83
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:


or like this


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:


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

Answer Source

Here you go:


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

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

for ($i = 0; $i < count($parts) - 1; $i ++) {
        echo $parts[$i] . '-' . $parts[$i + 1] . "\n";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download