Kirk Ouimet
Kirk Ouimet

Reputation: 28354

Check if a String Ends with a Number in PHP

I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.

function endsWithNumber($string) {
  $endsWithNumber = false;

  // Logic

  return $endsWithNumber;
}

Upvotes: 11

Views: 14461

Answers (6)

Sumit Kumar
Sumit Kumar

Reputation: 1902

This should work

function startsWithNumber(string $input):bool
{
      $out = false; //assume negative response, to avoid using else
      if(strlen($input)) {
        $out = is_numeric($input[0]); //only if string is not empty, do this to avoid index related errors.
      }
      
      return $out;
}

Upvotes: 0

shihab mm
shihab mm

Reputation: 525

in my opinion The simple way to find a string ends with number is

    $string = "string1";
    $length = strlen($string)-1;
    if(is_numeric($string[$length]))
    {
       echo "String Ends with Number";
    }

Upvotes: 1

XMehdi01
XMehdi01

Reputation: 1

Firstly, Take the length of string, and check if it is equal to zero (empty) then return false. Secondly, check with built-in function on the last character $len-1.

is_numeric(var) returns boolean whether a variable is a numeric string or not.

function endsWithNumber($string){
    $len = strlen($string);
    if($len === 0){
        return false;
    }
    return is_numeric($string[$len-1]);
}

Tests:

var_dump(endsWithNumber(""));
var_dump(endsWithNumber("str123"));
var_dump(endsWithNumber("123str"));

Results:

bool(false)
bool(true)
bool(false)

Upvotes: 0

Nanaki
Nanaki

Reputation: 21

To avoid potential undefined index error use

is_numeric($code[strlen($code) - 1])

instead.

Upvotes: 2

Kinjal Dixit
Kinjal Dixit

Reputation: 7935

$test="abc123";
//$test="abc123n";
$r = preg_match_all("/.*?(\d+)$/", $test, $matches);
//echo $r;
//print_r($matches);
if($r>0) {
    echo $matches[count($matches)-1][0];
}

the regex is explained as follows:

.*? - this will take up all the characters in the string from the start up until a match for the subsequent part is also found.

(\d+)$ - this is one or more digits up until the end of the string, grouped.

without the ? in the first part, only the last digit will be matched in the second part because all digits before it would be taken up by the .*

Upvotes: 8

Reese Moore
Reese Moore

Reputation: 11640

return is_numeric(substr($string, -1, 1));

This only checks to see if the last character in the string is numerical, if you want to catch and return multidigit numbers, you might have to use a regex.

An appropriate regex would be /[0-9]+$/ which will grab a numerical string if it is at the end of a line.

Upvotes: 29

Related Questions