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

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟