duanning9110 2016-09-21 09:36
浏览 17
已采纳

如何执行这两个功能?

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.

  • 写回答

1条回答 默认 最新

  • dongpo0409 2016-09-21 09:41
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题