How to remove last 3 characters from a string in PHP?
Hello everyone! I'm a beginner in PHP and working on a project where I need to process strings with data. I have a variable containing a string like "HelloWorld123". I need to remove the last three characters to get "HelloWorld". I've tried different methods, but nothing works correctly.\n\nFor example, I tried using substr() with a negative length value, but got confused with the parameters. Here's my code:\n\n```php\n$string = "HelloWorld123";\n$result = substr($string, 0, -3);\necho $result; // Outputs "HelloWorld" — this works, but I'm not sure if it's correct.\n```\n\nBut what if the string is shorter than 3 characters? For example, "ab"? I get an error. Or if I need to remove not 3, but a different number of characters depending on the condition? I've also heard about rtrim(), but it only removes spaces.
No answers yet.
Log in to leave an answer