In PHP, it is common to need to retrieve the last few characters of a string. This can be easily achieved using built-in functions. Below are two commonly used methods.
substr is a PHP function that returns a portion of a string. By passing a negative number as the start parameter, you can extract characters starting from the end of the string.
$str = "Hello World";
$last_chars = substr($str, -5);
echo $last_chars; // Outputs "World"
In the example above, -5 means to get the last 5 characters from the string.
If your string contains multibyte characters like Chinese, Japanese, or Korean, using mb_substr is a better choice to avoid character corruption. This function supports multibyte encodings.
$str = "你好,世界";
$last_chars = mb_substr($str, -2);
echo $last_chars; // Outputs "世界"
Besides getting the last few characters, sometimes you need to remove them. PHP built-in functions can also help with this.
substr_replace replaces part of a string with another string. By replacing characters at the end with an empty string, you effectively remove them.
$str = "Hello World";
$new_str = substr_replace($str, "", -5);
echo $new_str; // Outputs "Hello"
Here, -5 means replacing the last 5 characters with an empty string, thus deleting them.
rtrim removes specific characters from the right end of a string. This is useful for trimming unwanted characters but not suitable for removing by length.
$str = "Hello World";
$new_str = rtrim($str, "rld");
echo $new_str; // Outputs "Hello Wo"
In this example, the characters "r", "l", and "d" are removed from the right end.
Depending on your needs and character types, you can choose substr or mb_substr to get the last few characters, or substr_replace and rtrim to remove them. Using these functions appropriately helps efficiently manage string operations.