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.

1 Answer 1

3

Your friend is preg_match

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

See demo at eval.in

Sign up to request clarification or add additional context in comments.

5 Comments

God bless you, I will send you beer! Thank you, you are great! :)
one little question how I can get if $string = "Tes97779 test";
@diank In this case use lookarounds: /(?<!\d)\d{5,7}(?!\d)/ like in this demo at regex101. This one matches 5 to 7 digits not bordering at another digit.
@diank If you want to cut off the first ten, just remove the lookahead part (?!\d)
@diank Yer welcome! Also see the regex faq if interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.