How do I remove the last character only if it's a period?
$string = "something here.";
$output = 'something here';
How do I remove the last character only if it's a period?
$string = "something here.";
$output = 'something here';
using rtrim replaces all "." at the end, not just the last character
$string = "something here..";
echo preg_replace("/\.$/","",$string);
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 :-)
The last character can be removed in different ways, Here are some
rtrim()$output = rtrim($string, '.');
Regular Expressionpreg_replace("/\.$/", "", $string);
substr() / mb_substr()echo mb_substr($string, 0, -1);
echo substr(trim($string), 0, -1);
substr() with trim()echo substr(trim($string), 0, -1);
The chop() function removes whitespaces or other predefined characters from the right end of a string
$string = "something here.";
$string = chop($string,".");
echo $string;
Output
something here