Thursday, 2 January 2014

PHP: remove first and last lines

I end up consuming a lot of JSON both by JavaScript itself and also by PHP. The move towards callbacks within scripts means that I end up getting an awful lot of gumph returned alongside the meat of the JSON - thankfully most coders maintain the lovely formatting of the JSON and simply add a reference to the callback on the first line and then add an extra ); on the last line so that the code we get back from the remote server looks a little like this:

callback(
  /*[JSON HERE]*/
);

This leaves me wanting to remove the first and last lines of a string in order to get to the the JSON. Thankfully I found this post so I'll copy the solution here for the next time I need to do it:

<?php
  /*make an array*/
  $bits = explode("\n", $str);
  /*remove the first item*/
  array_shift($bits);
  /*remove the last item*/
  array_pop($bits);
  /*rebuild it*/
  $str = implode($bits);
?>

If, however, the return is all on one line like this:

callback(/*[JSON HERE]*/)

Then you'll need to alter the function to something like this:

<?php
  $str = substr($str, 0, -1);
  $str = substr($str, 9);
?>