Make string with ampersand work for email subject

Hi,
I have the following mailto link on a page:

<a href="mailto:?subject=<?= $page->title() ?> | <?= $site->title() ?>&body=<?= $page->url() ?>">
Email
</a>

Which works fine until the $page->title() contains an ampersand, at which point the subject is cut off. I know why this is, but am not sure what to use to manipulate $page->title() to fix this. I tried urlencode but then I get a load of + symbols for the spaces.

What is the best way of going about this?

You can use

htmlspecialchars($page->title())

https://www.php.net/manual/de/function.htmlspecialchars.php

Thanks for the reply.

I can see it is working in the source (replacing & with &amp;) but it is still truncating the email subject at that point.

Example of the outputted link here:

<a href="mailto:?subject=Some title &amp; something | Website&body=https://google.com">
    Email
  </a>

But when I click on it it is cutting off at Some title in the email subject

rawurlencode() seems to work…

Yes! That has done the trick, thank you