00 Votes

PHP: Remove arbitrary characters at the beginning and the end of a string

Tip by Stefan Trost | 2012-06-29 at 23:45

Sometimes we want to remove certain characters from a string from its front or its back. For example, spaces, white space, dashes or other characters.

Exemplary, we have the following strings:

$a = "  Front and Rear Spaces should be removed.  ";
$b = "-front-and-rear-dashes-should-be-removed-";
$c = " - Dashes and Spaces should be reomoved. - ";

From the first string, we would like to remove the front and rear spaces, from the second we would like to remove the front and rear dashes and from the third string, we want to remove both.

The following PHP code is doing this exactly:

$a = trim($a);      // "Front and Rear Spaces should be removed."
$b = trim($b, '-'); // "front-and-rear-dashes-should-be-removed"
$c = trim($c, '-'); // "Dashes and Spaces should be reomoved."

By using trim() without further parameters, only the front and rear spaces will be removed. In addition to the string, we can pass another parameter to trim() determining which character beside the spaces should also be removed. In the second and third example, we do this with '-', so that the front and rear dashes will be removed.

Only remove at the beginning or the end

With the function ltrim(), we can only delete those characters at the beginning. With rtrim(), we are deleting the characters only at the end of the string. Otherwise, these two functions are used in the same way as trim().


About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile


Related Topics


Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.