PHP chop function

 The PHP chop function can be used to remove blank characters from the end of string or delete specific specified characters. The chop function usage is exactly the same as the rtrim function. According to the official PHP website, the PHP chop function is the rtrim function. Alias ​​of rtrim , which means that these two functions are actually the same. The chop function is used to delete the white space at the end of the string or to remove the newline of HTML . The \n character is very concise and easy to use. It can handle a variety of characters without additional special characters.


PHP chop function syntax
chop( string $str [, string $charlist ] );
The first parameter $str of the PHP chop function is the string to be processed, so it must be filled in. The second parameter is optional. If it is not filled in, the chop function will automatically convert these characters "" ", \ t, \n, \r, \0, \x0B" are removed from the suffix of the $str string.

PHP chop function example
<?php
$text_str = "Welcome to Wibibi.\n";

$new_str_1 = chop($text_str);
var_dump($new_str_1);

echo '<br>';

$new_str_2 = chop($text_str,'.');
var_dump($new_str_2);

echo '<br>';

$new_str_3 = chop($text_str);
$new_str_3 = chop($new_str_3,'.');
var_dump($new_str_3);
?>
Example output
string(18) "Welcome to Wibibi."
string(19) "Welcome to Wibibi. "
string(17) "Welcome to Wibibi"
At the beginning of the example, a string $test_str is prepared, and then there are three groups of chop converted results. First, the first group does not use the second parameter in chop, so the chop function automatically changes the original string $test_str The "\n" newline symbol at the end of the suffix is ​​deleted, and the total number of characters processed by the chop function is 18 through var_dump. The second group is a little bit special, because we plan to directly let chop delete the comma (.) character, but found no effect. Why? Because the basic rule of the chop function is to delete characters from the end of the string, since the original character $test_str has a newline character (\n) at the end, it is reasonable to delete this newline character before deleting the comma, but the chop function Only one item can be deleted at a time, so if the newline character is not deleted, the comma cannot be deleted, which means that chop has no effect. In order to improve this situation, we used the chop function twice in the third group, first delete the newline character (\n), and then delete the comma (.), so the result will be only 17 characters left!

Post a Comment

0 Comments