Jump to content

[SOLVED] Array Key by alpha


xiaix

Recommended Posts

I have a string coming in from a database.  For example: a0b34c7d0e2333

 

What I would like to do is build an end result keyed array with that string, like this:

$dataArray = array("a" => "0", "b" => "34", "c" => "7", "d" => "0", "e" => "2333");

 

Since I don't have a valid delimiter for the explode function to work, I would like to know if I can use the letters (alpha) of the incoming string as a delimiter.

 

What coding hurdles would I need to convert my incoming string into that keyed array?  Is it even possible to do this?

 

I thank you for your time and review.

Link to comment
Share on other sites

Thank you for your very quick reply.

 

I could see str_split() working like I needed if my string were a one-to-one ratio, like: a4b2c5

 

But will str_split() still work the way I need it to if my string is: a4b24854c555  ?

Link to comment
Share on other sites

Here's one way,

 

<?php
$str = "a0b34c7d0e2333";

preg_match_all('/([a-z])([\d]+)/', $str, $part);
$out = array_combine($part[1], $part[2]);
      
print_r($out);
?>

 

Output

Array
(
    [a] => 0
    [b] => 34
    [c] => 7
    [d] => 0
    [e] => 2333
)

 

Link to comment
Share on other sites

Here's one way,

 

<?php
$str = "a0b34c7d0e2333";

preg_match_all('/([a-z])([\d]+)/', $str, $part);
$out = array_combine($part[1], $part[2]);
      
print_r($out);
?>

 

Output

Array
(
    [a] => 0
    [b] => 34
    [c] => 7
    [d] => 0
    [e] => 2333
)

 

You, my friend, are genius.  Worked wonderfully.  Thank you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.