my_string = '(增值税代码)地址(地址)034372 350-352 Vo Van Kiet, Co Giang Ward'
我当前的代码=
preg_replace('/[^0-9]/', '',my_string)
我当前的结果 = 034372350352 这是错误的输出
但我需要正确的结果 = 034372
如何使用 php 获取字符串中的第一个数字序列?
谢谢
Copyright 2014-2026 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] ); } }你是对的,我正在打电话。您应该考虑对此进行一些验证和错误处理。也许这个例子有助于实现这一点。