2

I have the following text as an example:

\n\t\t\t\t\t3 comments

Can anyone help me to construct PHP regex formula for extracting the number? (in this case number = 3)
The number can be prefixed by any text, but after the number there should be a <space> followed by comments.

Thanks.

3
  • Is it going to be a number up to 9, or any number? Commented Aug 3, 2011 at 7:15
  • any number starting from 0, so it might be 100 or so on Commented Aug 3, 2011 at 7:24
  • Okay, I posted a solution already, so that should do exactly that. :) Commented Aug 3, 2011 at 7:25

4 Answers 4

2
$text = '\n\t\t\t\t\t3 comments';
if (preg_match('/(\d+)\scomments/', $text, $match)) {
    $number = $match[1];
} else {
    // the number was not found
}

This will match any number if it exists in the string and will assign it to the variable $number. If the number was not found, you can handle it in the else statement.

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

2 Comments

it gives me "3 comments". I only need "3" as the output. BTW, I found that the one posted by Karolis is working. Thanks anyway for your attention.
@tukang-coding if you use $number = $match[1]; it will give you only the number, because this is stored in the capture group 1.
1
preg_match('/\d+(?= comments)/', $text, $match);

Comments

0
$str = "\n\t\t\t\t\t3 comments";
preg_match('/\.*(\d+)\scomments/',$str,$m);
var_dump($m[1]);

Comments

0
preg_match("/(\d+)\s+comments/", $text, $match);
print_r($match);

Comments

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.