Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get numbers from string using preg_match [closed]

Tags:

php

preg-match

I have a string :

 <div id="post_message_957119941">

I want to fetch only the numbers (957119941) from this string using preg_match.

like image 918
user2169679 Avatar asked Mar 14 '13 11:03

user2169679


People also ask

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.

How can I get only number from string in PHP?

We can use the preg_replace() function for the extraction of numbers from the string.

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

What does Preg_match return in PHP?

Definition and Usage The preg_match() function returns whether a match was found in a string.


1 Answers

This shouldn't be too hard.

$str = '<div id="post_message_957119941">';

if ( preg_match ( '/post_message_([0-9]+)/', $str, $matches ) )
{
    print_r($matches);
}

Output:

Array ( [0] => post_message_957119941 [1] => 957119941 )

So the desired result will always be in: $matches[1]

Is that what you need?

like image 142
w00 Avatar answered Sep 19 '22 03:09

w00