Last Updated: February 25, 2016
·
1.754K
· andreia

Only digits: Regex and filter_var

<?php

$str = '13++56-461.79/27--14-abc';

$filter = filter_var($str,FILTER_SANITIZE_NUMBER_INT);
$onlyDigitsFilterVar = str_replace(array('+', '-'), '', $filter);

$onlyDigitsRegexp1   = preg_replace('/[^\d]/', '', $str);
$onlyDigitsRegexp2   = preg_replace('/[^[:digit:]]/', '', $str); // http://www.php.net/manual/en/regexp.reference.character-classes.php

var_dump($filter);  // string(19) "13++56-4617927--14-"
var_dump($onlyDigitsFilterVar);  // string(13) "1356461792714"
var_dump($onlyDigitsRegexp1); // string(13) "1356461792714"
var_dump($onlyDigitsRegexp2); // string(13) "1356461792714"

1 Response
Add your response

$simpler_regex = preg_replace( '/\D/', '', $str);

over 1 year ago ·