1

I have a string and I want to get only number witch is between 5 and 7 charts. Here my problem:

$string = "Test 1 97779 test";
if(strlen(preg_replace("/[^0-9]/", "", $string)) >= 5 && strlen(preg_replace("/[^0-9]/", "", $parts[7])) <= 7) {
    $var = preg_replace("/[^\d-]+/", "", $string);
} 

Result is: 19779, but I want only 97779. If someone have any suggestion I will be very glad. Thanks in advance.

diank
  • 628
  • 2
  • 11
  • 19

1 Answers1

3

Your friend is preg_match

if(preg_match('/\b\d{5,7}\b/', $str, $out))
  $var = $out[0];

See demo at eval.in

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
  • God bless you, I will send you beer! Thank you, you are great! :) – diank Feb 05 '16 at 15:59
  • one little question how I can get if $string = "Tes97779 test"; – diank Feb 06 '16 at 10:38
  • @diank In this case use [lookarounds](http://www.regular-expressions.info/lookaround.html): `/(?<!\d)\d{5,7}(?!\d)/` like in this [demo at regex101](https://regex101.com/r/rE9vZ6/1). This one matches 5 to 7 digits not bordering at another digit. – bobble bubble Feb 06 '16 at 11:12
  • @diank If you want to cut off the first ten, just [remove the lookahead part (?!\d)](https://regex101.com/r/rE9vZ6/3) – bobble bubble Feb 06 '16 at 11:33
  • @diank Yer welcome! Also see the [regex faq](http://stackoverflow.com/a/22944075/5527985) if interested. – bobble bubble Feb 06 '16 at 12:03