2

I have a string that contains either an alphabet or a number.

AB1D21E48EFGHI1K

I am trying to break that string into array as follows.

[0] => A
[1] => B
[2] => 1
[3] => D
[4] => 21
[5] => E
[6] => 48
[7] => E
[8] => F
[9] => G
[10] => H
[11] => I
[12] => 1
[13] => K

But, I am getting array as follow:

[0] => Array (
    [0] => AB
    [1] => 1
    [2] => D
    [3] => 21
    [4] => E
    [5] => 48
    [6] => EFGHI
    [7] => 1
    [8] => K
)

I have tried the following code so far.

$string = 'AB1D21E48EFGHI1K';
preg_match_all('/([0-9]+|[a-zA-Z]+)/', $string, $matches);
print_r($matches);
3
  • your desired output? Commented Apr 16, 2017 at 10:43
  • 1
    Use ([0-9]+|[a-zA-Z]{1}) or simpler (\d+|\w{1}) Commented Apr 16, 2017 at 10:45
  • @Mohammad, Thank you. It helped Commented Apr 16, 2017 at 10:48

2 Answers 2

1

You should remove + after word character to matching with length 1. So your regex should be

/([0-9]+|[a-zA-Z])/

You can make your regex simpler to

/\d+|\w/

The code changed to

$string = 'AB1D21E48EFGHI1K';
preg_match_all('/\d+|\w/', $string, $matches);
print_r($matches);

Check result in demo

Sign up to request clarification or add additional context in comments.

3 Comments

[0-9]+|[a-zA-Z]
\w is NOT the same as [a-zA-Z]
@Toto You are right but in this case it worked properly.
1

Please try like this way, it might be useful for you

<?php
$data = array(0 => AB,1 => 1, 2 => D, 3 => 21, 4 => E, 5 => 48, 6 => EFGHI, 7 => 1, 8 => K);

/*print "<pre>";
print_r($data);
print "<pre>";*/


$new_data = array();
foreach($data as $key => $value){

  if (!preg_match('/[^A-Za-z]/', $value)) // '/[^a-z\d]/i' should also work.
  {
    // string contains only english letters
    $arr1 = str_split($value);
    foreach($arr1 as $row => $val){
      $new_data[] = $val;
    }
  }else{
    $new_data[] = $value;
  }

}

/*
 print "<pre>";
 print_r($new_data);
 print "<pre>";*/

?>

2 Comments

Where $data comes from?
According to above question, I have created a $data array in which data store in user questions format according .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.