Manipulating Strings with PHP

PHP provides many functions to manipulate strings. Here are some of the more common once.

Getting the Length of a String

strlen(s) – returns the length of the string specified as the argument

$s = "Sample String";
$len = strlen($s);

 

Trimming White-space from a String

White-space characters are: space, tab and linefeed that have no visual representation.

ltrim(s) – returns the value of string with white-space trimmed from the left end

rtrim(s) – returns the value of string with white-space trimmed from the right

trim(s) – returns the value of string with white-space trimmed from both end.

$s = "Sample string";

$new = ltrim($s); // returns "Sample string"

$new = rtrim($s); // returns "Sample string"

$new = trim($s); // returns "Sample string"

Converting Strings to Upper or Lowercase

strtoupper(s) – returns the value of it’s argument, converted to all uppercase

strtolower(s) – returns the value of it’s argument, converted to all lowercase

$s = "Sample string";

$new = strtoupper($s); // returns "SAMPLE STRING"

$new = strtolower($s); // returns "sample string"

Comparing Strings

strcasecmp(s1,s2) – Case-insensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match.

strcmp(s1, s2) –  Case-sensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match.

strncasecmp(s1,s2, n) – Case-insensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match. The maximum of n characters is included in the comparison. NOTE: this function was added in PHP version 4.0.2.

strncmp(s1, s2, n) – Case-sensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match. The maximum of n characters is included in the comparison.

Related Posts: