Reputation: 43778
Does anyone know how can I cut only number or char from the string in php?
$test = '12b';
any way that I can only cut the number from the variable: 12? also and way that I can only cut out the char: b?
NOTE: the $test string flexible to changed.. means it could come with '123b', '1a'...
Upvotes: 0
Views: 674
Reputation: 74252
preg_match
could be made use of:
<?php
$test = '12b';
preg_match( '/^(\d+)(\w+)$/', $test, $matches );
$digits = $matches[1];
$characters = $matches[2];
?>
Upvotes: 2
Reputation: 76756
Try this:
$test='12b';
// ...
$numeric = preg_replace('/[^\d]/', '', $test);
echo $numeric; // 12
$alpha = preg_replace('/[^a-z]/i', '', $test);
echo $alpha; // b
This will work for any combination of characters. All the digits will appear in $numeric, and all latin alphabet letters will appear in $alpha.
This will still work if the letters and numbers are reversed, or if other symbols appear in the string.
Upvotes: 1