Search code examples
phpstringicalendar

PHP prevent stripping spaces in only some situations


Im trying to build an iCal feed in PHP ... I've taken some instruction from tutorials and have the following code;

public function getEventsICalObject()
{
   $events = TechEvents::all();
   define('ICAL_FORMAT', 'Ymd\THis\Z');

   $icalObject = "BEGIN:VCALENDAR
   VERSION:2.0
   METHOD:PUBLISH
   PRODID:-//Testing Calendar//Tech Events//EN\n";
  
   // loop over events
   foreach ($events as $event) {
       $icalObject .=
       "BEGIN:VEVENT
       DTSTART:" . date(ICAL_FORMAT, strtotime($event->starts)) . "
       DTEND:" . date(ICAL_FORMAT, strtotime($event->ends)) . "
       DTSTAMP:" . date(ICAL_FORMAT, strtotime($event->created_at)) . "
       SUMMARY:$event->summary
       UID:$event->uid
       STATUS:" . strtoupper($event->status) . "
       LAST-MODIFIED:" . date(ICAL_FORMAT, strtotime($event->updated_at)) . "
       LOCATION:$event->location
       END:VEVENT\n";
   }

   // close calendar
   $icalObject .= "END:VCALENDAR";

   // Set the headers
   header('Content-type: text/calendar; charset=utf-8');
   header('Content-Disposition: attachment; filename="cal.ics"');
  
   $icalObject = str_replace(' ', '', $icalObject);

   echo $icalObject;
}

This works great and outputs perfect except for one thing, at the bottom of the function it uses str_replace to strip spaces to make the output validate ... The problem is if the $event->summary or $event->location has any spaces in it, it strips them out too making the whole thing pointless.

Is there any way to prevent these from being stripped?


Solution

  • Assuming it's the start of the lines that you want to clean up, use following code:

    $icalObject = preg_replace("/([\n\r]+)[ ]+/s","$1", $icalObject);
    

    this will remove your spaces from the line beginnings.