How do you split a string based on the number of letter characters and/or the number of numbers so that they are separate strings?
Hopefully this makes sense. Thanks for any help (:
For example:
The user inputs:
- Henry, Smith ID: 123456
I would like to sort the user input into separate strings with the result of:
$name = 'Henry, Smith';
$ID = '123456';
You can use regex to match only numbers and everything but numbers.
Note, for the
name, this will returnHenry, Smith ID:from your question’s example. This just takes the numbers out… it doesn’t know “ID:” isn’t part of a person’s name.Explanation of the caret (
^):Inside the brackets it means match everything NOT in the brackets. So
[^0-9]matches everything but numbers. In this example, it’ll replace everything that isn’t a number with a blank (second parameter). For the$name, we do the opposite. We replace everything that IS a number with a blank to just get the non-digit characters.See here for more info on regex.