PHP 字符串函数在数字转换为字符串时无法按预期工作

发布于 2024-11-26 17:05:25 字数 320 浏览 3 评论 0原文

我有以下代码,在邮政编码中放置一个空格。

(string)$postcode = $row['postcode'];
$first = substr($postcode, strlen($postcode)-3);
$second = substr($postcode, strlen($first));
$postcode = $first . ' ' . $second;

除了某些代码之外,该代码对于大多数代码都可以正常工作。即

PN45HA 70448

我不明白为什么?任何人都可以阐明这一点吗?

谢谢

I have the following code which places a space in postcode.

(string)$postcode = $row['postcode'];
$first = substr($postcode, strlen($postcode)-3);
$second = substr($postcode, strlen($first));
$postcode = $first . ' ' . $second;

The code works fine for most codes, except some. ie

PN45HA
70448

And i can't understand why? Can anyone shine a light on this?

Thankyou

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

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

发布评论

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

评论(3

握住你手 2024-12-03 17:05:25

不太明白这个问题,但如果是关于空间的,这会起作用:

$postcode = 'PN45HA70448';
$postcode = substr($postcode, 0, -3) . ' ' . substr($postcode, -3);
// PN45HA70 448

Don't really understand the question, but if it's about the space, this will work:

$postcode = 'PN45HA70448';
$postcode = substr($postcode, 0, -3) . ' ' . substr($postcode, -3);
// PN45HA70 448
魔法少女 2024-12-03 17:05:25
$first = substr($postcode, 0, -3);
$second = substr($postcode, -3);
$postcode = $first . ' ' . $second;
$first = substr($postcode, 0, -3);
$second = substr($postcode, -3);
$postcode = $first . ' ' . $second;
茶花眉 2024-12-03 17:05:25
$code = 'PN45HA 70448'
$first = substr($postcode, strlen($postcode)-3); // 448
$second = substr($postcode, strlen($first)); // PN45HA 70
$postcode = $first . ' ' . $second; // PN45HA 70 448

问题是并非所有邮政编码都是简单的 6 字符邮政编码。您只需在传入的任何字符串的最后 3 个字符之前添加空格即可。

您可能需要做的是使用正则表达式:

$code = preg_replace('/([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])/', '\1 \2', $code);

这将采用任何看起来像邮政编码的字符串,两半之间有可选的空格,并放入一个空格中。

$code = 'PN45HA 70448'
$first = substr($postcode, strlen($postcode)-3); // 448
$second = substr($postcode, strlen($first)); // PN45HA 70
$postcode = $first . ' ' . $second; // PN45HA 70 448

The problem is that not all of your postcodes are simple 6 character postcodes. You're simply adding space before the last 3 characters in whatever string you happen to pass in.

What you may need to do is use a regex:

$code = preg_replace('/([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])/', '\1 \2', $code);

This'll take any string which looks like a postcode, with optional spaces between the two halves, and puts in a single space.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文