Search code examples
phpstringtext-extractiontext-parsing

Get hyphen-separated integers from inside parentheses in a string


I have a string something like this:

$string = "small (150 - 160)"

Is there a way I could store 150 in the variable $min and 160 in the variable $max in php?


Solution

  • function minMax($string) {
      $digits = explode("-", $string);
      return filter_var_array($digits, FILTER_SANITIZE_NUMBER_INT);
    }
    
    // $yourString = "small (150 - 160)"
    $values = minMax( $yourString );
    $min = $values[0]; $max = $values[1];
    

    The function uses explode to remove "-" and create an array. The string to left of "-" is placed in $digits[0] and to right in $digits[1].

    PHP filters are then used to remove non integer characters from the array strings. Note I assume you are working with whole numbers. filter_var_array won't work with decimal points but you can use filter_var instead with the FILTER_SANITIZE_NUMBER_FLOAT flag to retain decimals points.

    function minMax($string) {
      return filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
    }
    
    $values = minMax( "small (150 - 160.4)" );
    $number = explode("-", $values);
    $min = $number[0]; $max = $number[1];
    

    In the decimal example immediately above any "." will be retained. If strings can contain non numeric periods then you will need to remove leadin "."s from your output e.g. if string = "big... (150 - 160.4)" then $min will contain '...150' to prevent leading periods $min = trim($min,'.');.