![]() Wanting the ability to return back the original string unaltered if search char/string not found. Removing from left or right side of string (first or last occurrence). "!!Something!!". Using strripos/strrpos when character/string not found in string. "!!Something!!".TrimLeadingCharacter('!') // Result '!Something!!' (Only 1st instance removed) "!Something!".TrimEndsCharacter('!') // Result 'Something' (End Characters removed) "!Something!".TrimTrailingCharacter('!') // Result '!Something' (Last Character removed) Remove the last character by PHP rtrim() PHP rtrim() accepts two arguments: the input string and characters you wish to be stripped from the end of the input string. Let’s begin with my favorite option: the rtrim function, a.k.a the right trim. "!Something!".TrimLeadingCharacter('!') // Result 'Something!' (1st Character removed) In this quick guide, we’ll try three ways of removing the last character(s) from a string in PHP. "!Something!".TrimEndsCharacter('g') // Result '!Something!' (No Change) You can find last character using php many ways like substr() and mbsubstr(). If length is given and is positive, the string returned will contain at most length characters beginning from offset (depending on the length of string ). The only solution I could think of was explode and then grab the first part of the array but thats not the most elegant solution. I had a look on the php.net site and did a google search but couldnt find anything. "!Something!".TrimTrailingCharacter('S') // Result '!Something!' (No Change) Is there a php string function to trim a string after a particular character. Usage "!Something!".TrimLeadingCharacter('X') // Result '!Something!' (No Change) Private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) & value = character What is fastest way to remove the last character from a string I have a string like a,b,c,d,e, I would like to remove the last ',' and get the remaining string back: OUTPUT: a,b,c,d,e What is the fastest way to do this php csv delimiter truncate trailing Share Improve this question Follow edited at 9:23 mickmackusa 43. Public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target Public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target ![]() Public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character) An example Extension class to simplify this: - internal static class String ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |