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?
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})