随着答案的改进
https://stackoverflow.com/a/26809278/16566807
脚本会产生一些在包含时可能有用的格式。脚本符合 BASH 规范,用 shellcheck 检查。
#!/bin/bash
#
#
X=("hello world" "goodnight moon" 'say "boo"' 'foo\bar')
#
# set parameter to define purpose: return_format
# php5 -> for 5.x
# -> https://stackoverflow.com/questions/7073672/how-to-load-return-array-from-a-php-file/7073686
# php -> for 7.x and greater
# json -> for $array=@file_get_contents($f); json_decode($array, true);
# /none/ -> for JS to JSON.Parse(myJSON);
# function call with array as parameter: return_array "${array[@]}"
return_array() {
rf="${return_format}"
if [[ $rf = "php5" ]]; then
q=("<?php return array(" ");")
elif [[ $rf = "php" ]];then
q=("<?php return [" "];")
elif [[ $rf = "json" ]];then
q=("{" "}")
else
q=("[" "]")
fi
echo -n "${q[0]}"
while [[ $# -gt 0 ]]; do
x=${1//\\/\\\\}
echo -n "\"${x//\"/\\\"}\""
[[ $# -gt 1 ]] && echo -n ', '
shift
done
echo "${q[1]}"
}
echo "PHP 5.x"
return_format="php5"
return_array "${X[@]}"
echo "PHP 7.x"
return_format="php"
return_array "${X[@]}"
echo "JSON for PHP"
return_format="json"
return_array "${X[@]}"
echo "JSON for JS"
return_format=
return_array "${X[@]}"
将产生输出:
PHP 5.x
<?php return array("hello world", "goodnight moon", "say \"boo\"", "foo\\bar");
PHP 7.x
<?php return ["hello world", "goodnight moon", "say \"boo\"", "foo\\bar"];
JSON for PHP
{"hello world", "goodnight moon", "say \"boo\"", "foo\\bar"}
JSON for JS
["hello world", "goodnight moon", "say \"boo\"", "foo\\bar"]