-3

I have strings with the following pattern: 12345ABCDE6789 where each group of numbers and letters are a variable length. There will only ever be numbers and letters, no special characters.

I need a way to get the numbers up until the first letter, so that the example above would return 12345.

My thought was I could find the string position of the first letter and then trim the string to that position. But I'm having trouble figuring out how to get that index without knowing what the character is. Other solutions I've found have had the knowledge that the first letter would be an "A" where mine could be any letter.

Is there a concise way to do this?

I do not have much experience with regex, but maybe something there would be a better solution to this problem?

fonini
  • 3,243
  • 5
  • 30
  • 53
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43

2 Answers2

5
<?php

$re = '/^[0-9]+/m';
$str = '12345ABCDE6789';

preg_match($re, $str, $matches);

var_dump($matches[0]); // 12345

https://regexr.com/4mcfr

fonini
  • 3,243
  • 5
  • 30
  • 53
3

So long as the number will be <= 2147483647 for 32 bit systems and <= 9223372036854775807 for 64 bit, then the simplest is to cast to an integer and it will truncate letters (anything that will not return a valid integer):

echo (int)"12345ABCDE6789";

Returns 12345

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87