ds11111111111111111 2017-03-09 14:46
浏览 34
已采纳

使用固定位置恢复字符串中的数据

I have a file that contains data at fixed positions (no separator).

for exemple:

$string = '0412345678Mr foo    25.2';

with

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)

I can do that:

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

It's work fine.

I would like to know if there is an another to do this.

I try that:

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

But that don't work.

If I replace spaces with another character like _, that's work but I don't want change data.

Another Idea? Regular expression?

  • 写回答

1条回答 默认 最新

  • duanbixia7738 2017-03-09 14:58
    关注

    As you mentioned it, you could use regexp. Here is an example of a simple one that would work :

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

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

    With the addition of http://php.net/manual/fr/function.preg-match.php, that could do the trick.

    Then if you want them inside your variable simple assign them by taking the output of 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);
    

    By the way, you can replace [0-9] by "\d" etc ... Which could give :

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决