Reputation: 141
Let's say i have an example text like this "1-10 this is a text 1000 records."
how can I get the number 10 from it using regular expression im using PHP. is
preg_match('/[^-0-9]/', '', $text)
good ?
Upvotes: 0
Views: 109
Reputation: 18357
Unlike preg_replace
preg_match
function takes first argument as the regex that needs to be matched, second argument as the string in which the regex is applied for matching and third argument is the variable where the matches will be stored. For capturing 10
out of 1-10 this is a text 1000 records.
, you can exploit the occurrence of -
just before the digit you intend to capture and can write a regex like this,
-(\d+)
Which basically will look for a hyphen -
and will capture whatever number having 1 or more digits in group1. In php you can access it like this,
$s = "1-10 this is a text 1000 records.";
preg_match('/-(\d+)/', $s, $m);
print($m[1]); // m[0] will contain full match and m[1] will contain text matched by group1
Which prints,
10
Upvotes: 1