php basic String functions

June 6, 2016

updated 2020-08-28

strlen, strcmp, substring, strtoupper, strtolower, str_replace, addslashes, trim, strstr, strpos, str_repeat, strrev, explode, implode, chunk_split, . . .

 

string length

$length = strlen($str);

an empty string

if( empty($string) ) :

A variable is empty if it’s undefined, null, false, 0 or an empty string.

 

substring


$str = "abcdefgh";
echo substr($str, 1);
// bcdefgh
echo substr($str, 3); // defgh
echo substr($str, -1); // h
echo substr($str, 2, 4); // cdef (starting point, length)
echo substr($str, strlen($str)-4, 4); // efgh
echo substr($str, strlen($str)-$length, $length); // if $length=3: fgh


$ph = '8001234444';
if ( ctype_digit($ph) AND strlen($ph) == 10 ) :
$viewph = SUBSTR($ph, 0,3).'-'.SUBSTR($ph, 3,3).'-'.
SUBSTR($ph, 6,4) ;
// 800-123-4444
endif;


$pho = '00448001234444';
if ( ctype_digit($pho) AND strlen($pho) > 10 ) :
$seepho = substr($pho, 0, strlen($pho)-10 ) .'-'.
substr($pho, strlen($pho) - 10, 3) .'-'.
substr($pho, strlen($pho) - 7, 3) .'-'.
substr($pho, strlen($pho) - 4, 4);
$changed = 'yes' ;
endif;

 

compare


if (strcmp("Joe", "joe") != 0 )
echo 'the 2 are not =' ; # they are not =

if ($string1 == $string2)
echo 'the 2 are =' ; # they are =

in alpha. order … A < a
$str1 = ‘Alan’;
$str2 = ‘alan’;
if ($str1 <= $str2)
$list .= ‘ ‘.$str1.’ ‘.$str2 ;
ELSE
$list .= ‘ ‘.$str2.’ ‘.$str1 ;


if ( $string1 <> $string2 )
echo 'string1 is not the same as string2';

strncmp() – Binary safe string comparison of the first n characters
strcmp() is similar to the strncmp() function, with the difference that you can specify
the number of characters from each string to be used in the comparison with strncmp().

 

case-insensitive compare

strcasecmp() – Binary safe case-insensitive string comparison

$str1 = 'ApAchE';
$str2 = 'apache';
if (strcasecmp($str1, $str2) == 0)
echo 'the 2 are =' ; # they are =
ELSE
echo 'the 2 are not =' ;


$str1 = "red";
$str2 = "redent";
$test=strncasecmp($str1, $str2 , 3); # the first 3 characters are compared
if ($test <= 0 )
$list .= ' '.$str1.' '.$str2 ; in alpha. order
ELSE
$list .= ' '.$str2.' '.$str1 ; in alpha. order

The strcasecmp() function is a built-in function in PHP and is used to compare two given strings. It is case-insensitive. This function is similar to strncasecmp(), the only difference is that the strncasecmp() provides the provision to specify the number of characters to be used from each string for the comparison.

 

Strip all characters but letters from a PHP string
$result = preg_replace(“/[^a-zA-Z]/”, “”, $string);

Strip all characters but letters and numbers from a PHP string
$result = preg_replace(“/[^a-zA-Z0-9]/”, “”, $string);

Strip all characters but numbers from a PHP string
$phone = preg_replace('/\D+/', '', $phone) ;

 

stristr


$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}

// output: “earth” not found in string

 

substr_count

Count the number of substring occurrences

$text = 'This is a test';
echo substr_count($text, 'is');
# echo 2

Count the number of carriage returns in a string

substr_count($aString, "\n") ;

in php 5.1 the offset and the length parameters were added
so that you can check only part of a string
example: an offset of 3 means start checking at the 4th position
example: an offset of 3 means skip the first 3 positions

// generates a warning because 5+10 > 14 . . . and the strlen = 14

$text = 'This is a test';
echo substr_count($text, 'is', 5, 10);

 

FIND: strpos

to find where it is (if it exists) the occurrence of one string inside other:
example 1:

if (strpos($string, 'substring') !== false)
{ echo 'true'; }

Note that the use of !== false is deliberate; strpos returns either the offset at which the substring begins in the $string, or the boolean false if the substring isn’t found. Since 0 is a valid offset, 1st position in the $string, we can’t use simpler constructs like !strpos($astring, ‘ substring ‘) – – which makes strstr() a simpler alternative for relatively short strings. see below
Also, the difference between != and !==
is that != is for comparing two different types of variables for example: if you are comparing an integer and a string use != and it will still work if you comparing a string and a string or a var() and a var()
What a !== does is only compare the same type so it wont work with a var() and a string

example 2:

if ( stripos($_SERVER['SERVER_NAME'], 'website') !== false )
{ $mesg = 'on website'; }
else
{ $mesg = 'not on website'; }

example 3:

if ( stripos('mywebsite', 'myweb') !== false )
{ $mesg = 'in website'; }
else
{ $mesg = 'not in website'; }

$mesg will return “in website” eventhough it starts in position 0
because 0 is not the same data type as false.
one is an integer and the other is boolean.

 

strstr

for short strings, strstr may be better than dealing with “strpos() !==false”

The strstr() function scans a string for a particular pattern and returns the contents
of that string from the point onwards (for the case-insensitive version, use stristr()).

$str = “As Mulder keeps saying, the truth is out there”;
echo strstr($str, "the");
// returns “the truth is out there”

 

strpos

the strpos() function to locate the first occurrence.

$str = "Robin Hood and his band of merry men";
echo strpos($str, "R");
// returns 0 == false – however, “R” was found.

if ( stripos($str, 'R') !== false )
{ $mesg = 'found'; }
else
{ $mesg = 'not found'; }

and the strrpos() function to locate its last occurrence.

$str = "Robin Hood and his band of merry men";
echo strrpos($str, "m");
// returns 33 (the last one)

referencing the characters in a string: (as an array)

$fname = 'Harry';
echo $fname[0];
echo $fname{0};
echo substr($fname, 0, 1);

all 3 echo ‘H’


$str="12345-characters";

for($i=0;$i<strlen($str);$i++)
{
echo "position $i: ".$str{$i}."\n";
}

Note the {$i} instead of [$i] for strings.

 

strtoupper, strtolower


$firstname = 'Harry';
if ( $firstname == strtoupper($firstname) OR
$firstname == strtolower($firstname) )
echo 'all upper or all lower';
else
echo ' not up/low Harry ';

# However, a MySQL query for a string is Not case sensitive!

ucfirst() == upper case the 1st char (ignore the rest)
ucwords() == UpperCase 1st letter of Words (ignore the rest)
ucwords(strtolower()); == lowercase all, then upper case the 1st chars
ucfirst(strtolower()); == lowercase all, then upper case the 1st char

str_replace


$str = "yo ho ho and a bottle of gum";
$str = str_replace("gum", "rum", $str);
echo $str ;

// returns “yo ho ho and a bottle of rum”

Replace the characters “world” in the string “Hello world!” with “Peter”:

$strvar = "Hello world!" ;
$strvar = str_replace("world", "Peter", $strvar);

// use str_ireplace() for the case insensitive version

$name = str_replace(” “, “”, $_POST[‘name’]); # remove all blanks

for complicated replacements involving regular expressions, see preg_replace

trim

$str = ” ever seen a white pigeon? “;
echo trim($str); # returns “ever seen a white pigeon?”
trim() removes blanks from both ends.
You can use the ltrim() and rtrim() functions, to
remove whitespace only from the beginning or end of a string respectively.

strstr

The strstr() function scans a string for a particular pattern and returns the contents
of that string from the point onwards (for the case-insensitive version, use stristr()).

$str = “As Mulder keeps saying, the truth is out there”;
echo strstr($str, "the");
// returns “the truth is out there”

str_repeat

// displays “howdy ” 22 times
echo str_repeat("howdy ", 22);

strrev

to reverse a string: ( from “123” to “321” etc. )
$rts = strrev($str);

explode

$str = “Rachel, Monica, Phoebe, Joey, Chandler, Ross”;

// split into array

 $arr = explode(", ", $str);

 foreach($arr as $friend)
    {
    echo " $friend";
    }
implode

creates a single string from all the elements of an array, joining them
together with a user-defined separator. Reversing the example above, we have:

$arr = array(“Rachel”, “Monica”, “Phoebe”, “Joey”, “Chandler”, “Ross”);

// create string from array
$str = implode(” and “, $arr);

echo “$str are friends”;
// returns “Rachel and Monica and Phoebe and Joey and Chandler and Ross
// are friends”

chunk_split

You can use this function to split a string into smaller chunks of a fixed size,
echo chunk_split($str, 11);

string padding

$str = “123.45”;

echo str_pad($str, 9);
// returns “123.45 ”

echo str_pad($str, 9, "0");
// returns “123.45000”

echo str_pad($str, 9, "0", STR_PAD_LEFT);
// returns “000123.45”

printf() directly outputs the result

printf is short for “print, formatted”.

printf( "%04d", 12 ); // Displays “0012”

printf( "%02d", 2 ); // Displays “02”

as a precision specifier:
printf( "%.2f", 123.456 ); // Displays "123.46"
printf("%.10f", 123.456 ); // Displays "123.4560000000"
printf( "%.0f", 123.456 ); // Displays "123"

If you use a padding specifier with a precision specifier then printf() pads the entire value, including the decimal point and decimal digits, to the specified length:

printf( "%08.2f", 123.456 ); // Displays “00123.46”

printf("Hello %s, How's it going?", 'Joe');

sprintf()

identical to printf(), except that rather than directly outputting the result, it returns it so that you can store it in a variable (or otherwise manipulate it). This is useful if you want to process the result before displaying it, or store it in a database.
sprintf() can be remembered using the phrase “silent printf()”, because the only difference is that sprintf() doesn’t output anything to the browser so can be saved in a variable.
sprintf is unsafe because it doesn’t check the length of the destination buffer. This can cause the function to overflow the destination buffer when the result of the format string is unexpectedly long, leading to security issues and application instability.
snprintf and sprintf_s are safe alternatives to sprintf


$result = sprintf( "Australia comprises %d states and %d territories", 6, 10 );
echo $result;

// Displays “Australia comprises 6 states and 10 territories”

%,8d for instance to get the rightly aligned 8 digit and commas separated integer.

logging in – and filling out a form

mysql_real_escape_string, prepends backslashes to the following characters: \x00, \n, \r, \, ‘, ” and \x1a. It is “used to make data safe before sending a query to MySQL”.

addslashes() Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte).

The PHP directive magic_quotes_gpc was on by default (is now deprecated, will not exist in php 6), and it essentially ran addslashes() on all GET, POST, and COOKIE data.

stripslashes($str); removes all the backslashes and returns a “clean” string.

$lastname = addslashes($_POST['lastname']);

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you’re entering data into a database.

For example, to insert the name O’reilly into a database, you will need to escape it. Most databases do this with a \ which would mean O\’reilly. This would only be to get the data into the database, the extra \ will not be inserted.

as of PHP6, the magic_quotes… functions have been dropped.

If you have old code that might use or check for “magic_quotes_gpc” etc., you probably should scan you code for “magic_quotes” and make plans for removing it. … before they crash.

Always turn it off in a PHP.ini file and then, when PHP6 arrives, you only have the one file to ‘adjust’.

php.ini:
magic_quotes_gpc = Off
magic_quotes_sybase = Off

——————————————————————
global alternative?:
$postarray = array_map(‘addslashes’, $_POST)
——————————————————————

strip_tags

The strip_tags() function finds and removes all HTML and PHP tags that may be embedded within a string.
example:

$str = "<table><tr><td>Name</td><td>Price</td></tr></table>";
echo strip_tags($str);

// returns NamePrice

nl2br

the nl2br() function automatically replaces blank lines in a string with the corresponding HTML line break tag <br>

$str = ” green \n yellow \n blue \n red \n ” ;

echo nl2br($str);
// returns ” green <br> yellow <br> blue <br> red <br> ”

Leave a Reply

We try to post all comments within 1 business day