Encoding mailto: Subject Lines Bookmark

I was working on a very simple “email this article as a recommendation” feature, where the user would click a link to open their email client with a pre-populated subject and email body. The link looks like this:

<a href="mailto:?subject=SUBJECT_TEXT&body=BODY_TEXT"

The issue I ran into showed up when the article title contained special characters and especially an ampersand (&), since that would cut off the subject line, because it would signal the beginning of the next paramater. This feature is for a Kirby site and I tried a few different PHP encodings to get around this problem. One of the obvious things to try was to urlencode() the string. Since urlencode() replaces the spaces with a “+” sign, it wasn’t the right choice. Eventually the solution was to use PHP’s rawurlencode() for the subject text, which uses “%20” for spaces which are later invisible in the subject line.