preg_match 一个包含重复数据的字符串

发布于 2024-11-27 03:59:11 字数 318 浏览 3 评论 0原文

例如我有下一个字符串:

2556974513|0123254852|1025635214|1236521025|0124576832

字符串中必须是 10 位,然后是 | 并且这个公式可能会重复 n 次,如何匹配它?

也许有一个最简单的方法可以做到这一点,比这个:

preg_match('/^[\d]{10}|[\d]{10}| ... [\d]{10}$/', $string);

谢谢。

For example i have next string :

2556974513|0123254852|1025635214|1236521025|0124576832

in the string must be 10 digits then | and this formula may be repeated n times, how to match it?

maybe there is an easiest way to do that, than this :

preg_match('/^[\d]{10}|[\d]{10}| ... [\d]{10}$/', $string);

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

粉红×色少女 2024-12-04 03:59:11

您将需要这样的内容:

^(?:\d{10}\|)+\d{10}$

末尾的 \d{10} 存在,因为末尾没有 | 字符。 + 将匹配前面的一个或多个模式。如果仅匹配一组 10 位数字是有效的,则将 + 替换为 *,这将匹配零次或多次。

请注意,| 字符需要转义,因为它在正则表达式中用作 OR 运算符。

You will want something like this:

^(?:\d{10}\|)+\d{10}$

The \d{10} at the end is there since there is no | character at the end. The + will match one or more of the preceding pattern. If it is valid to match only one group of 10 digits then replace the + with * which will match zero or more times.

Note that the | character needs to be escaped, because it is used as an OR operator in regex.

找回味觉 2024-12-04 03:59:11

这意味着“一个或多个(10 位数字然后管道)”:

(\d{10}\|)+

编辑:从您的问题中不清楚尾矿管是否存在。如果没有,那么:

(\d{10}\|)*(\d{10})

另外,如果您仍然需要提取值,您也可以这样做:

foreach (explode('|', $string) as $value) {
    if (preg_match('/^\d{10}$/', $value)) {
        ...
    }
}

This means "one or more of (10 digits then pipe)":

(\d{10}\|)+

Edit: It's not clear from your question if the tailing pipe will be there or not. If not, then:

(\d{10}\|)*(\d{10})

Also, if you need to extract the values anyway, you may as well just do:

foreach (explode('|', $string) as $value) {
    if (preg_match('/^\d{10}$/', $value)) {
        ...
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文