JS:将JS对象格式化为php语法形式(完美支持无unicode编码匹配的正则)
/**
* 格式化Object数据为php语法形式
* @param {*} obj 任意数据
* @param {String} spaceLen 缩略符长度:必须在2~65536之间,否则默认为2
* @return {String} 格式化后的PHP语法字符串
*/
function formatToPhp(obj, spaceLen) {
formatToPhp = function (obj, spaceLen) {
const space =
spaceLen >= 2 && spaceLen <= 65536 ? ' '.repeat(spaceLen) : ' '
return formatToPhp.fn(obj, '', (formatToPhp.space = space))
}
formatToPhp.toStr = function (scalar) {
scalar = JSON.stringify(scalar).split('\'').join('\\\'')
return '\'' + scalar.slice(1, -1) + '\''
}
formatToPhp.fn = function (obj, minSpace, maxSpace) {
const t = typeof obj
if (t === 'object') {
const nextSpace = maxSpace + this.space
switch (Object.prototype.toString.call(obj)) {
case '[object Array]':
return obj.length === 0
? '[]'
: `[\n${maxSpace}${obj.map((item) => this.fn(item, maxSpace, nextSpace)).join(`,\n${maxSpace}`)}\n${minSpace}]`
case '[object Object]':
const keys = Object.keys(obj)
return keys.length === 0
? '[]'
: `[\n${keys.map((key) => maxSpace + this.toStr(key) + ' => ' + this.fn(obj[key], maxSpace, nextSpace)).join(',\n')}\n${minSpace}]`
case '[object RegExp]':
return '\'' + (obj + '').split('\'').join('\\\'') + '\''
}
return null
} else if (t === 'string') return this.toStr(obj)
return t === 'function' ? 'function(){}' : JSON.stringify(obj) || null
}
return formatToPhp(obj, spaceLen)
}
注意:正则在匹配unicode编码时需要手动修改。例如:
JS正则:/[\u4e00-\u9fa5]+/
PHP正则:/[\x{4e00}-\x{9fa5}]+/u