How do I remove extra spaces at the end of a string using regex (preg_replace)?
$string = "some random text with extra spaces at the end      ";
                There is no need of regex here and you can use rtrim for it, its cleaner and faster:
$str = rtrim($str);
But if you want a regex based solution you can use:
$str = preg_replace('/\s*$/','',$str);
The regex used is /\s*$/
\s is short for any white space
char, which includes space.* is the quantifier for zero or
more$ is the end anchorBasically we replace trailing whitespace characters with nothing (''), effectively deleting them.
You don't really need regex here, you can use the rtrim() function.
$string = "some random text with extra spaces at the end      ";
$string = rtrim($string);
Code on ideone
See also :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With