How do I remove all specific characters at the end of a string in PHP?
How do I remove the last character only if it's a period?
$string = "something here.";
$output = 'something here';
$output = rtrim($string, '.');
(Reference: rtrim on PHP.net)
using rtrim replaces all "." at the end, not just the last character
$string = "something here..";
echo preg_replace("/\.$/","",$string);
To remove the last character only if it's a period and not resorting to preg_replace
we can just treat the string as an array of char and remove the final character if it is a dot.
if ($str[strlen($str)-1]==='.')
$str=substr($str, 0, -1);
I know the question is solved. But maybe this answer will be helpful for someone.
rtrim()
- Strip whitespace (or other characters) from the end of a string
ltrim()
- Strip whitespace (or other characters) from the beginning of a string
trim()
- Strip whitespace (or other characters) from the beginning and end of a string
For removing special characters from the end of the string or Is the string contains dynamic special characters at the end, we can do by regex.
preg_replace
- Perform a regular expression search and replace
$regex = "/\.$/"; //to replace the single dot at the end
$regex = "/\.+$/"; //to replace multiple dots at the end
$regex = "/[.*?!@#$&-_ ]+$/"; //to replace all special characters (.*?!@#$&-_) from the end
$result = preg_replace($regex, "", $string);
Here is some example to understand when $regex = "/[.*?!@#$&-_ ]+$/";
is applied to string
$string = "Some text........"; // $resul -> "Some text";
$string = "Some text.????"; // $resul -> "Some text";
$string = "Some text!!!"; // $resul -> "Some text";
$string = "Some text..!???"; // $resul -> "Some text";
I hope it is helpful for you.
Thanks :-)