0

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.

5 Answers 5

1

list($speciesname, $date, $locationcode, $city) = explode('-', $filename);

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this is working exactly as needed. Thank you everyone else for their help as well.
1

Use PHP explode

$pieces = explode('-', 'species_name-date-locationcode-city');
$name = $pieces[0];
$data = $pieces[1];
$code = $pieces[2];
$city = $pieces[3];

Comments

1
<?php
$myvar = 'common_daisy-20130731-ABCD-Dallas';
$tab = explode ('-', $myvar);
$speciesname = $tab[0];
$date = $tab[1];
$locationcode = $tab[2];
$city = $tab[3];
?>

Comments

1

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];

Comments

0

http://php.net/manual/en/function.explode.php

$pieces = explode("-", $description);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.