In PHP, we can use various methods to convert a string into an array of integers.
A common way is to use the explode()
function to split the string into arrays according to the specified delimiter, and then use the array_map()
function to split each Elements are converted to integer types. As shown below:
$str = '1,2,3,4,5'; $arr = explode(',', $str); $arr = array_map('intval', $arr);
Another way is to use regular expressions to extract the numbers in the string, and then use the array_map()
function to convert each number to an integer type. As shown below:
$str = 'abc123def456ghi789'; preg_match_all('/\d+/', $str, $matches); $arr = array_map('intval', $matches[0]);
You can also use the preg_split()
function to split the string into arrays according to regular expressions, and then use the array_map()
function to split each elements are converted to integer types. As shown below:
$str = 'a1b2c3d4e5'; $arr = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); $arr = array_map('intval', $arr);
Another way is to use the str_split()
function introduced in PHP 7 to split the string into an array of individual characters and then use array_map( )
function converts each character to an integer type. As shown below:
$str = '12345'; $arr = str_split($str); $arr = array_map('intval', $arr);
No matter which method is used, the string can eventually be converted into an integer array, which facilitates our subsequent processing.
The above is the detailed content of How to convert php string to int array. For more information, please follow other related articles on the PHP Chinese website!