可能重复:
a simple function for return number from string in phpPHP:最好的方法来从字符串中提取数字
什么是最好/最有效的方法来从字符串中提取一组特定的数字?例如:我希望在案例#之后立即得到一组数字,在sring“blah blah Case#004522 blah blah”中。我想像例子#之后的数字字符总是一样的,但我希望代码不要像以前那样做这个假设。
到目前为止,我一直在使用strpos方法来定位案例#再拉个字符的具体数目后记使用SUBSTR。我只是觉得这很笨重。也许preg_match会更有效或简化?
$text = "blah blah Case#004552 blah blah";
$find = strpos($text,'Case#');
if ($find)
$numbers = substr($text, $find+5, 6);
'的preg_match('/ \ d + /',$ str,$ match);' - '$ match [0]'将包含字符串中的第一个连续数字组。 – DaveRandom 2012-07-20 14:19:55
取决于您对“最佳”的定义。你的意思是最快吗?我认为strpos应该是在另一个字符串中查找特定字符串的最快方法,假设将该数字视为以字符串开头(比preg_match快)。 – Rhys 2012-07-20 14:23:39
@Ryven:最佳在该特定情况下是用的preg_match作为阵列中获得可能的多个匹配被一个未考虑奖金。 – Brad 2012-07-20 14:34:55