Ryan decosta
Ryan decosta

Reputation: 455

converting .string file format into php array format

Hope that you are doing file

So here is my question i have a xyz.string file that is used for translation.Please find the a small part of file below.

/* name for an item that is duplicated in the UI, based on the original name */
"%@ (Copy)" = "%@ (kopi)";

/* display name for a book page template that is the first page of that section */
"%@ (First)" = "%@ (Første)";

/* display name for a book page template that represents a hardcover cover. the second argument is the cover type. */
"%@ (Hardcover, %@)" = "%1$@ (Hard innbinding, %2$@)";

/* display name for a book page template that represents a softcover cover. the second argument is the cover type. */
"%@ (Softcover, %@)" = "%1$@ (myk innbinding, %2$@)";

i want to convert the translation i.e in a php array like

array(
array{
"%@ (First)"=>"%@ (Første)"
},
array
{
"@ (Hardcover, %@)"=>"%1$@ (Hard innbinding, %2$@)"
}
)

and so on.The format that is specified is not mandatory but it should be something that i can workaround with.

Following is the specification of the file format

I know this can be achieved through PREG_MATCH_ALL but i am not able to create a nice regular expression

below is my code

$str=file_get_contents($_FILES['string']['tmp_name']);
preg_match_all("|(\".+\"\;)|s",preg_quote($str),$match);
echo "<pre/>";print_r($match);die;

the exact string i am getting after file_get_content is following

/* name for an item that is duplicated in the UI, based on the original name */ "%@ (Copy)" = "%@ (kopi)"; /* display name for a book page template that is the first page of that section */ "%@ (First)" = "%@ (Første)"; /* display name for a book page template that represents a hardcover cover. the second argument is the cover type. */ "%@ (Hardcover, %@)" = "%1$@ (Hard innbinding, %2$@)";

If anyone can help me in this it will be much appreciated

Thanks Ryan

Upvotes: 0

Views: 231

Answers (2)

revo
revo

Reputation: 48721

The Lord, Regex:

"([^"]+)"\s*=\s*"([^"]+)";

Explanations:

"([^"]+)"     # Every thing between double quotes
\s*=\s*       # Equal sign preceded or followed by any number of spaces
"([^"]+)";    # Again every thing between double quotes that ends to a ;

PHP code:

$text = file_get_contents($_FILES['string']['tmp_name']);
preg_match_all('#"([^"]+)"\s*=\s*"([^"]+)";#', $text, $match);
$translate = array_combine($match[1], $match[2]);
print_r($translate);

The output for your sample text will be:

Array
(
    [%@ (Copy)] => %@ (kopi)
    [%@ (First)] => %@ (Første)
    [%@ (Hardcover, %@)] => %1$@ (Hard innbinding, %2$@)
    [%@ (Softcover, %@)] => %1$@ (myk innbinding, %2$@)
)

Upvotes: 1

Yami
Yami

Reputation: 1425

You could just read the wohle string and then use: explode

$array = explode(';', $string);

Upvotes: 0

Related Questions