Alternatively, the ltrim() and rtrim() functions can be used for trimming specific sides of your strings. The PHP trim() function provides simple functionality that packs a punch when you need something quick and useful to clean up your data. Resulting in the following output: This is a strĪs you can see, the text "ing" is now omitted from our resulting string, showing a partially removed sentence. You can specify certain characters to remove from a string, as well: $string = "This is a string" echo trim($string, "ing") The output for the above example will show as follows: This is a string To remove whitespace from both sides of a string, use the following example: $string = " This is a string " echo trim($string) Here are a few examples you can use when passing in a value for the $chars parameter: If this parameter is left empty, the function will remove whitespace from both sides of a string by default. The function trims each element using the trim. The following runnable example displays an array of strings before and after applying a function on each element. By default, it will strip: Spaces ' 'New lines Carriage returns \r Tabs \t Vertical tabs \v NULL characters \0 Codebyte Example. $chars: An optional parameter where you can pass in specific characters to remove. A range of characters can be specified with. ![]() $string: A required, hard-coded string or variable containing the text you want to remove whitespaces or characters.Here is a breakdown of each of the parameters: The syntax for the PHP trim() function looks like this: trim($string, $chars) ![]() The trim() function in PHP removes whitespace and any other specified characters from both the left and right sides of a string.Īlternatively, you can use the ltrim() function to remove whitespace from only the left side of a string and rtrim() to remove whitespace from only the right side of a string. The trim() function removes any whitespace surrounding a string's value, resulting in a correctly stored value in the database table. I find this method particularly useful in cases where an application accepts user input to store in a database. In this tutorial, we'll look into how you can remove whitespace and other characters from a string using the trim() function in PHP.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |