I’m using php to create some strings I need to split() with javascript.
example:
<?php
$string = "Apples";
$string .= "|"; // delimiter
$string .= "Oranges";
$string .= "|"; // delimiter
$string .= "Grapes";
?>
and here I split the string with JS:
<script>
var str = <?php echo $string; ?>
var fruitsArray = str.split('|');
for(var i=0; i<fruitsArray.length; i++){
// do stuff here
}
</script>
In this case, the pipe character is the delimiter. But I could use any special character.
My problem is when the $string has a character I use for splitting AND it’s also part of the non-delimiter portion.
For example:
<?php
$string = "Apples";
$string .= "|"; // delimiter
$string .= "Oranges";
$string .= "|"; // delimiter
$string .= "Grapes";
$string .= "|"; // delimiter
$string .= "Berries: blue|black"; // pipe exists, but not meant to be a delimiter
?>
It’s circumstantial only, but does happen to me. My delimiters sometimes find their way into the fruits. (though I am only using fruits as an example)
I feel I need to convert my designated delimiters to another format before javascript gets a hold of it. But I’m not certain.
Anyone know what’s best in this situation?
Try use a more mature way of marshaling variables into javascript. Like json.
To convert a php array to json: http://php.net/manual/en/function.json-encode.php
To get an array from json in javascript:
var fruitArray = <?php echo json_encode(array('Apples', 'Oranges')); ?>;