【问题标题】:Recover data in a string with fixed positions恢复具有固定位置的字符串中的数据
【发布时间】:2023-03-20 18:48:01
【问题描述】:

我有一个文件,其中包含固定位置的数据(无分隔符)。

例如:

$string = '0412345678Mr foo    25.2';

code  = '04'       (integer with 2 characters)
ref   = '12345678' (string  with 8 characters)
name  = 'Mr foo  ' (string  with 8 characters)
price = '  25.2'   (double  with 6 characters)

我能做到:

$code  = (int) substr($string, 0, 2);
$ref   = substr($string, 2, 8);
$name  = substr($string, 10, 8);
$price = (double) substr($string, 18, 6);

一切正常。

我想知道是否有其他人可以这样做。

我试试:

list($code, $ref, $name, $price) = sscanf($string, "%2d%8s%8s%6s");

但这不起作用。

如果我用另一个字符(如 _)替换空格,这是可行的,但我不想更改数据。

另一个想法?正则表达式?

【问题讨论】:

  • 规则 10: 如果它没有坏,不要修理它!
  • 您可以通过使用您提到的正则表达式来做到这一点。 ([0-9]{2})([0-9]{8})([a-zA-Z ]{8})([0-9. ]{6})regex101.com/r/2bS8af/1
  • @kaldoran:我尝试过,但我不知道如何将结果放入变量中

标签: php regex optimization


【解决方案1】:

正如您所提到的,您可以使用正则表达式。 这是一个可行的简单示例:

([0-9]{2})([0-9]{8})([a-zA-Z ]{8})([0-9. ]{6})

https://regex101.com/r/2bS8af/1

加上http://php.net/manual/fr/function.preg-match.php,就可以解决问题了。

然后,如果您希望它们在您的变量中,只需通过获取 preg_match 的输出来分配它们:)

<?php
$string = '0412345678Mr foo    25.2';

$pattern = '/([0-9]{2})([0-9]{8})([a-zA-Z ]{8})([0-9. ]{6})/';
preg_match($pattern, $string, $matches);
print_r($matches);

顺便说一句,您可以将 [0-9] 替换为 "\d" 等... 哪个可以给:

(\d{2})(\d{8})([\w\s]{8})([\d\s.]{6})

https://regex101.com/r/2bS8af/3

【讨论】:

  • 谢谢,我测试了preg_split,但没有测试preg_match
  • 没问题 :) 我通过使用 \d、\w 等添加了一个更简单的版本 :)
  • 非常感谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2016-10-20
  • 1970-01-01
  • 2022-01-24
  • 2021-05-30
  • 1970-01-01
相关资源
最近更新 更多