I have some regex patterns stored as strings inside a PHP array. I need them to be outputted as JavaScript RegExp objects. Is there any way to do this by using PHP's json_encode
?
Example:
$array = [
'regex' => '/some-regex/'
];
return json_encode( $array );
Desired output:
{"regex": /some-regex/}
Current output:
{"regex": "/some-regex/"}
No, you can't. Because you're passing through JSON structure which just wraps-data. A string by json standard starts with " and ends with ", otherwise it's a number or an array for istance.
I wondered a similiar thing about it. I wanted to create a function for JS but on server side with php, based on the result. Usually when you face this problem it means you've to rethink a bit the structure of your page/app.
However as they pointed out in the comments to your question, you might find workarounds to build the object locally once the HTTP request is ended.
Also would recommend reading this: Security issues JSON with eval
Not directly with json_encode
. All PHP does is create arrays and objects containing simple scalar types. It cannot create JS objects like RegExp
or call JS functions directly. If all you're going to pass is that sample data in the question you can always do
$array = [
'regex' => '/some-regex/'
];
$js_string = '';
foreach($array as $key => $value) $js_string .= '"' . $key . '": new RegExp("' . $value ' "),';
return '{' . $js_string . '}';
That's really clunky code and, of course, it falls apart if $array
contains anything but regular expressions (and it assumes that everything in there is safe for JS). But if that's all you have to do...
Indeed there is. The better thing to do is have json_encode
do it's thing (it's kinda made to handle JSON) and then have your JS create the objects itself
let regex_list = <?php echo json_encode($array) ?>;
let myregex = {};
regex_list.forEach(function(regex, index) {
myregex[index] = new RegExp(regex);
});
This is a much cleaner solution. We don't have to worry about the data coming from PHP, so JS can take it from there and build a JS object that holds all the RegExp
objects you want to create