如何执行这两个功能?

时间:2016-09-21 09:36:10

标签: php regex

是否可以在正则表达式中执行这两个函数转换?

// 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   

我试过编码我需要做的这两个例子。 非常感谢。

1 个答案:

答案 0 :(得分:1)

使用preg_match在您的功能中捕捉它们。

用于捕获字母的正则表达式:

/([A-Z]+)/i

用于捕获数字的正则表达式:

/([0-9]+)/

所以你可以拥有以下功能:

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];
}

你会像这样使用它:

echo getAlpha("butterfly12"); //butterfly
echo getNumeric("butterfly12"); //12

修改

我现在认为我理解你的意思,也许这些功能最适合你:

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;
}