Reputation: 1
Using PHP, I am looking to parse a string and convert it into variables. Specifically, the string will be a file name, and I'm looking to break the file name into variables. Files are nature photos, and have a uniform format:
species_name-date-locationcode-city
All files names have this exact format, and the "-" is the delimiter. (I can make it whatever if necessary)
an example of the file name is common_daisy-20130731-ABCD-Dallas
I want to break it up into variables for $speciesname, $date, $locationcode, $city.
Any idea on how this can be done? I have seen functions for parsing strings, but they usually take the form of having the name of the variable in the string, (For example "species=daisy&date=20130731&location=ABCD&city=Dallas") which I don't have, and cannot make my file names match that. If I wanted to use a string replace to change the delimiters to variables= I would have to use 4 different delimiters in the filename and that wont work for me.
Thanks for anyone who tries to help me with this issue.
Upvotes: 0
Views: 132
Reputation: 71384
You can explode the string on delimiter and then assign to variables
$filename = 'species_name-date-locationcode-city';
$array = explode('-', $filename);
$speciesname = $array[0];
$date = $array[1];
$locationcode = $array[2];
$city = $array[3];
Upvotes: 1
Reputation: 904
<?php
$myvar = 'common_daisy-20130731-ABCD-Dallas';
$tab = explode ('-', $myvar);
$speciesname = $tab[0];
$date = $tab[1];
$locationcode = $tab[2];
$city = $tab[3];
?>
Upvotes: 1
Reputation: 6353
Use PHP explode
$pieces = explode('-', 'species_name-date-locationcode-city');
$name = $pieces[0];
$data = $pieces[1];
$code = $pieces[2];
$city = $pieces[3];
Upvotes: 1
Reputation: 1511
list($speciesname, $date, $locationcode, $city) = explode('-', $filename);
Upvotes: 1
Reputation: 9710
http://php.net/manual/en/function.explode.php
$pieces = explode("-", $description);
Upvotes: 0