Mary Reejo R
Mary Reejo R

Reputation: 7

How to separate string from a long string in php

i have a string like

[email protected][email protected][email protected]~9127282

And the results should be

[email protected]~9999111132
[email protected]~047027282
[email protected]~9127282

Upvotes: 0

Views: 42

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94642

Something simple like this would do it

$in = '[email protected][email protected][email protected]~9127282';

$bits = explode('~', $in);

$newArr = [];

for ($i=0; $i<count($bits); $i+=4){
    // if you want results in an array
    $newArr[] = sprintf('%s~%s~%s~%s', $bits[$i], $bits[$i+1], $bits[$i+2], $bits[$i+3]);
}
print_r($newArr);

RESULT

Array
(
    [0] => [email protected]~9999111132
    [1] => [email protected]~047027282
    [2] => [email protected]~9127282
)

COMMENT ADDITION

Just change the code in the for loop to make an array in the format you like

for ($i=0; $i<count($bits); $i+=4){
    $newArr[] = ['id'=> $bits[$i],
                 'name'=> $bits[$i+1],
                 'email'=> $bits[$i+2],
                 'mobileno'=> $bits[$i+3]
      ];
}

RESULT NOW

Array (
    [0] => Array (
            [id] => 1
            [name] => anil
            [email] => [email protected]
            [mobileno] => 9999111132
        )
    [1] => Array (
            [id] => 2
            [name] => nikhil
            [email] => [email protected]
            [mobileno] => 047027282
        )
    [2] => Array (
            [id] => 3
            [name] => nimmy
            [email] => [email protected]
            [mobileno] => 9127282
        )
)

Upvotes: 2

Related Questions