本文介绍了在第一次出现标识符后获取字符串中的第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究一个获取这样的字符串的函数:
I'm working on a function that gets a string like this:
identifier 20 j. - cat: text text text aaaa dddd ..... cccc 60' - text, 2008并提取数字 20 所以字符串中第一次出现 identifier 之后的第一个数字(包括空格)
and extracts the number 20 so the first number in the string right after the first occurrence of identifier (including whitespace)
但是如果我有这样的字符串:
But if I had a string like this:
identifier j. - cat: text text text aaaa dddd ..... cccc 60' - text, 2008函数应该返回NULL,因为identifier(包括空格)出现后没有数字
the function should return NULL because there is no number right after the occurrence of identifier (including whitespace)
你能帮我吗?谢谢
推荐答案您可以为此使用正则表达式:
You can use a regular expression for this:
$matches = array(); preg_match('/identifier\s*(\d+)/', $string, $matches); var_dump($matches);\s* 是空格.(\d+) 匹配一个数字.
\s* is whitespace. (\d+) matches a number.
您可以将其包装在一个函数中:
You can wrap it in a function:
function matchIdentifier($string) { $matches = array(); if (!preg_match('/identifier\s*(\d+)/', $string, $matches)) { return null; } return $matches[1]; }更多推荐
在第一次出现标识符后获取字符串中的第一个数字
发布评论