Search code examples
phpstringstrip

Extracting a part of a string in php


I have a specific need to strip characters from a PHP input.

For example, we have a version number and I only need the last part of it.

Given 14.1.2.123 I only need 123
Given 14.3.21 I only need the 21

Is there a way that I can get just those numbers in PHP?


Solution

  • You can try this -

    $temp = explode('.', $version); // explode by (.)
    echo $temp[count($temp) - 1]; // get the last element
    
    echo end($temp);
    

    Or

    $pos = strrpos($version, '.'); // Get the last (.)'s position
    echo substr(
         $version, 
         ($pos + 1), // +1 to get the next position
         (strlen($version) - $pos) // the length to be extracted
    ); // Extract the part
    

    strrpos(), substr(), strlen(), explode()