Problem:
You told users not to add any number at the end in a form field. But, few users mistakenly did that. Now, you need a way to remove those numbers and get the remaining characters.
Solution:
Use chop() function in php
Example:
<?php $user_input = “Thank you123”; echo chop($user_input, “0..9”); ?>
Output:
Thank you
How it works:
chop() function can take two parameters and it removes second parameter(here 0..9) from the end of the first parameter. As there is 123 at the end of Thank you123, so it removes 123 and returns the “Thank you” only.
Caution 1: Characters in the parameters are case sensitive. In the following example, the capital letter Y in the first parameter will not be removed. By indicating small letters (a..z) in the second parameter, the function tells to remove only the small letters at the end of the first parameter.
Example:
<?php $user_input = “Thank You”; echo chop($user_input, “a..z”); ?>
Output:
Thank Y
Caution 2: The function removes characters from the end of the first parameter as long as it finds any unmatched character. So, it will not remove other matching characters that exist before that unmatched character.
Example:
<?php $user_input = “Thank You”; echo chop($user_input, “a..z”); ?>
Output:
Thank Y
In the above example, though there are small letters (hnak) exist before Y, but, it is not removed as capital Y is not told to remove and it stops there.
chop() function at a glance
(PHP4, PHP5)
Usages:
chop() function is used to remove trailing spaces or any predefined character(s) at the end of a string.
Syntax:
chop(string, charlist)
Parameters:
Parameter | What it does | |
string | Required | Define the string to check |
charlist | Optional | Specify which characters to remove from the string |
With or without the optional parameter
Function | 1st parameter | 2nd parameter | What it does | Example |
chop(string) | Without 2nd parameter, the following characters are removed at the end of string(1st parameter)
“\x0B” – vertical tab. |
chop(“Morning ”) Output: Morning (Note: In the output, there is no space after the word Morning) |
||
Chop(string, charlist) | It removes charlist at the end of string | chop(“Hello World”, “World”) Output: Hello |