获取可选冒号前的所有字母

I have a wrapper for PHPExcel, and I have a method called setColumn(), which looks like this:

public function setColumn($cell = ""){
    if(empty($cell)){
        $cell = $this->cell;
    }
    $this->column = strtoupper(preg_replace("/[^A-Za-z]/", "", $cell));
    $this->cell   = "{$this->column}{$this->row}";
    return $this;
}

It works just fine, but as I use it, I can pass in ranges such as A1:D1 and when I do, my preg_replace will not replace correctly, it will return AD which I don't want. I want it to return A. I am not sure of the regular expression needed to accomplish this.

The parameter $cell can contain a few different values:

  • A1 should return A
  • A1:D10 should return A
  • AD10 should return AD
  • AD1:BBB1 should return AD

The list could go on, but that is the basics. So what can I do to acomplish that?

Try:

preg_replace("/^([A-Z]+).*$/", "$1", $cell)

It'll 'save' the first part and remove everything else.

regex101 demo.

Matches the digit than an optional colon then everything after that

preg_replace("/\d:?.*/", "", $cell); 

Or as linepogl points out just

preg_replace("/\d.*/", "", $cell); 

as long as the pattern stays: letter(s) number everythingelse

I was able to come up with another solution, (Almost instantly after I submitted the question). What I did was explode on the : and used the first item in the array like this:

public function setColumn($cell = ""){
    if(empty($cell)){
        $cell = $this->cell;
    }
    $rng          = explode(":", $cell);
    $this->column = strtoupper(preg_replace("/[^A-Za-z]/", "", $rng[0]));
    $this->cell   = "{$this->column}{$this->row}";
    return $this;
}

To explain what you are doing and what you want to be doing I've explained the regex below.

Your REGEX says to replace all characters that are NOT (indicated by the ^) in the array [A-Za-z] a capital letter or lower case letter. Example

What you want is to remove everything from where the first instance a number is parsed. To match on a number use \d. To match on any character use . To match 0 or more of the preceeding token use *. This is a greedy match, and will match as many characters as possible before satisfying the next token.

If we combine .* this will match everything following.

To put it together /\d.*/ should accomplish this. Solution

Then

preg_replace("/\d.*/", "", $cell);