简体   繁体   English

如何在 PHP 的字符串数组中获取某个数值?

[英]How get a certain numeric value inside array of string in PHP?

I have a String $line .我有一个字符串$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.根据 var $line ,字符串有 6 个词,2 个数值,1 个数字和字符串的组合词。

I would like to catch a certain string which is a numeric value 12345 .我想捕捉某个字符串,它是一个数值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 .而不是12345

So, What is the 'Regular Expression' should I use, if I only like to catch string contain: 12345 ?那么,如果我只想捕获字符串包含: 12345 ,我应该使用什么“正则表达式”?

You could use word boundaries \b and match 4 or more digits using a quantifier {4,}您可以使用单词边界\b并使用量词匹配 4 个或更多数字{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 Output

array(1) {
  [0]=>
  string(5) "12345"
}

Php demo Php 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM