I have a String $line
. For example,
$line = "stringA stringB 4-stringC stringD stringF 12345 stringG 678249 stringH ";
According to the var $line
, there are 6 words of string, 2 numeric values, and 1 combination word of numeric and string.
I would like to catch a certain string which is a numeric value 12345
. And this is my code that I just tried:
if (preg_match('/ ([0-9,]+)/', $line, $matches) === 1 && strlen($matches[0]) > 3 && strlen($matches[1]) > 3) {
echo var_dump($matches[0]);
}
However, It seems like the code only take the first numeric value on the string, once it traced. And the result is:
array(2) {
[0]=>
string(2) " 4"
[1]=>
string(1) "4"
}
instead of 12345
.
So, What is the 'Regular Expression' should I use, if I only like to catch string contain: 12345
?
You could use word boundaries \b
and match 4 or more digits using a quantifier {4,}
\b\d{4,}\b
For example
$line = "string string 4-string string string 12345 string 678249 string ";
if (preg_match('/\b\d{4,}\b/', $line, $matches)) {
var_dump($matches);
}
Output
array(1) {
[0]=>
string(5) "12345"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.