my_string = '(增值税代码)地址(地址)034372 350-352 Vo Van Kiet, Co Giang Ward'
我当前的代码=
preg_replace('/[^0-9]/', '',my_string)
我当前的结果 = 034372350352 这是错误的输出
但我需要正确的结果 = 034372
如何使用 php 获取字符串中的第一个数字序列?
谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
<?php // make a service class or trait or package with a format enum by country could be useful. Also if you add the functionality to implement it into Laravel. class VatService { function getVatId(string $hayStack, string $needle = '/\d+/', bool $validateCount = false, $count = 6): string { return ( preg_match($needle, $hayStack, $matches) && ( $count == strlen($matches[0])) && $validateCount ) ? $matches[0] : throw new Exception('VaT number was not found : ' . $count . ' == ' . strlen($matches[0]) . ' ' . $matches[0] ); } }你是对的,我正在打电话。您应该考虑对此进行一些验证和错误处理。也许这个例子有助于实现这一点。
您可以使用 preg_match 来执行此操作。如果将第三个参数 ($matches) 传递给 preg_match,它将创建一个填充搜索结果的数组,并且 $matches[0] 将包含与完整模式匹配的第一个文本实例。
如果字符串中可能没有数字,您可以使用如下 if 语句来识别这些情况:
if (preg_match($pattern, $my_string, $matches)) { echo $matches[0]; } else { echo "No match found"; }参见https://www.php.net/manual/ en/function.preg-match.php