is possible perform these two function converting in a regular expression?
// Get all alpha-substring to left and before of any digits
// otherwise return empty string.
function ex1($source) {
$string_alpha = "";
$tmp = substr($source, 0, strcspn($source, '0123456789'));
if (ctype_alpha($tmp)) {
$string_alpha = $tmp;
}
return $string_alpha;
}
// Get all numeric-substring to right and after last letter
// otherwise return empty string.
function ex2($source) {
$string_numeric = "";
$tmp = substr($source, strcspn($source, '0123456789'));
if (ctype_digit($tmp)) {
$string_numeric = $tmp;
}
return $string_numeric;
}
$source = "butterfly12";
echo "ex1 function => " . ex1($source) . "<br>";
echo "ex2 function => " . ex2($source) . "<br>";
// Output:
// ex1 function => butterfly
// ex2 function => 12
I have tried to code about i need to do with these two example. Thanks very much.
Use preg_match to capture them in your functions.
Regex for capturing the letters:
/([A-Z]+)/i
Regex for capturing the numbers:
/([0-9]+)/
So you could have functions like:
function getAlpha($source) {
preg_match("/([A-Z]+)/i", $source, $matches);
return $matches[1];
}
function getNumeric($source) {
preg_match("/([0-9]+)/", $source, $matches);
return $matches[1];
}
And you would use it like this:
echo getAlpha("butterfly12"); //butterfly
echo getNumeric("butterfly12"); //12
EDIT
I now think I understand what you mean, perhaps these functions would work best for you:
function getAlpha($source) { //Gets whatever text is before a number.
$alpha = "";
if(preg_match("/^([A-Z]+)\d+/i", $source, $matches)) {
$alpha = $matches[1];
}
return $alpha;
}
function getNumeric($source) { //Gets whatever number is after the text.
$numeric = "";
if(preg_match("/(\d+)$/", $source, $matches)) {
$numeric = $matches[1];
}
return $numeric;
}