Home > Software engineering >  How can I take the last digits of this string
How can I take the last digits of this string

Time:12-16

How can I take the last digits of this string in PHP?

I want to create a student id for this I use the if else statement if the student table is empty then the first value will be for22dl1 after that you it will increase like for22dl2 in the next row.

Examples: string = for22dl1 output = 1

String = for22dl120 output = 120

// Generate Student ID
$year=date('y');
$sql = "select sno from students ORDER BY sno DESC LIMIT 1";
$result = mysqli_query($con,$sql);
$id=mysqli_fetch_array($result);
if(mysqli_num_rows($result) >0){
  //found
  $id = $id['student_id'];
  // here i want to write code for get the last digits after dl
  $sid = $id   1;
  $string="for$year dl$sid";
  $student_id = preg_replace('/\\s /', '', $string);

}else{
  //not found
  $string="for$year dl1";
  $student_id = preg_replace('/\s /', '', $string);
}

CodePudding user response:

Thanks Now its working for me:

    $regex = '/dl(\d )/';
    preg_match($regex, $id, $matches); 
    $matches=array_shift($matches);
    // output was dl220 (string   digit) Now filter the digit only 
    
    $int = (int) filter_var($matches, FILTER_SANITIZE_NUMBER_INT);
    $sid = $int   1;
    $string="for$year dl$sid";
    $student_id = preg_replace('/\s /', '', $string);

CodePudding user response:

$matches is resulted array, matches [0] is a string starting from dl to onward and matches[1] is your last integer value

  // Use preg_match() to extract the last digits from the string
  $regex = '/dl(\d )/';
  preg_match($regex, $id, $matches); 
  •  Tags:  
  • php
  • Related