PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

[FIXED] How do I split the letters and numbers to 2 arrays from a string in PHP

 May 17, 2022     php     No comments   

Issue

I would like to know how to split both letters and numbers in 2 separate arrays, for example if I have $string = "2w5d15h9s";, then I want it to become

$letters = ["w", "d", "h", "s"];

$numbers = [2, 5, 15, 9];

Anybody got any idea of how to do it?

I'm basically trying to make a ban command and I want to make it so you can specify a time for the ban to expire.


Solution

Use preg_split:

$string = "2w5d15h9s";
$letters = preg_split("/\d+/", $string);
array_shift($letters);
print_r($letters);
$numbers = preg_split("/[a-z]+/", $string);
array_pop($numbers);
print_r($numbers);

This prints:

Array
(
    [0] => w
    [1] => d
    [2] => h
    [3] => s
)

Array
(
    [0] => 2
    [1] => 5
    [2] => 15
    [3] => 9
)

Note that I am using array_shift or array_pop above to remove empty array elements which arise from the regex split. These empty entries occur because, for example, when spitting on digits the first character is a digit, which leaves behind an empty array element to the left of the first actual letter.



Answered By - Tim Biegeleisen
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing