There is no need for a regular expression, and you can use rtrim to make it cleaner and faster:
$str = rtrim($str);
But if you want to use a regex-based solution, you can use:
$str = preg_replace('/\s*$/','',$str);
Regular expression used /\s*$/
\s for any char space that includes space.* - quantifier for zero or more$ is the ultimate anchor
We basically replace the trailing space characters with nothing ( '' ), effectively removing them.
codaddict
source share