Lifestohack
Lifestohack

Reputation: 375

Create an array of each character and its following character from an input string

I have a string

$str = "Diwas"

I want to make an array of every two alphabet so I used

str_split($str, 2);

So my array will be now

Di
wa
s

But I want to make an array in such a way that the result will be.

Di
iw
wa
as
s

Upvotes: 0

Views: 60

Answers (2)

FrancoisBaveye
FrancoisBaveye

Reputation: 1902

This one is more ressource friendly than a preg_*

$str="Diwas"

$myArray = array();

for ($i = 0; $i < strlen($str); ++$i)
    $myArray[] = substr($str, $i, 2);

Upvotes: 3

n-dru
n-dru

Reputation: 9430

You can use preg_match_all:

$str="Diwas";
preg_match_all('/(?=(\w\w?))/',$str, $matches);
print_r($matches[1]);

Yields:

Array ( [0] => Di [1] => iw [2] => wa [3] => as [4] => s )

Upvotes: 3

Related Questions