PHP String

PHP String (Single Quote)

Create PHP String

echo 'A string literal';

echo 'Multiple
lines';

echo 'It\'s Sunday';                    # Escape character

PHP String Concatenation

'This ' . 'is ' . 'one ' . 'sentence';  # 'This is one sentence'

$s = 'hello';
$s .= ' world';                         # 'hello world'

Access character of a PHP String

$s    = '123';
$s[0] = 'a';                            # $s = 'a23'

PHP String (Double Quote)

"Double Quote" interprets more escape sequences and utilize variable evaluation

echo "Double quote allows more escape character like \t and \n";

PHP string with variable substitution

$str = 'text';

# Also allow string evaluation
$v1 = "String is $str";          # 'String is text'
$v2 = "String is {$str}";        # Same
$v3 =  "String is ${str}";       # Same

$v = 10;
$s = "$v";                       # String "10"

Use {} to avoid ambiguity

$s = "Value is {$val['count']}"  # {} is required
$s = "Value is {$val}s"

Use {} to delimit an expression which otherwise may have ambiguity expression

PHP Heredoc

Use a string delimiter to define the boundary of a String

$str = <<<SOMEDELIMITER
Use delimiter
for a
string
SOMEDELIMITER;

Use string delimiter with variable substitution

# $str will be evaluated similar to the double quote
$str = 'text';
$r = <<<EOS
Some embedded
string $str
Or
{$obj->name[0]}s
EOS;

Nowdoc (PHP 5.3+)

In Nowdoc, variable will NOT be evaluated

$str = <<<'SOMEDELIMITER'
The $str will be displayed
as
$str
SOMEDELIMITER;

Conversion between PHP array and string

Split a PHP string into multiple elements of an array using a delimiter

$r = explode(':', 'John:Paul:Mary');    # array(3) { [0]=> string(4) "John"
                                        #      [1]=> string(4) "Paul" [2]=> string(4) "Mary" }

Expand an array to a string separated by the string in the first parameter ','

implode(',' , array('a','b','c','d'));  # 'a,b,c,d'
$s = join(':', $r);                     # Same as implode

Traverse a PHP string using delimiter

$s = "John:Paul:Mary";
$next  = strtok($s, ":");
while ($next !== false) {               # Return one token at a time
      echo $next;
      $next = strtok(":");
}

Scanning a PHP String into multiple variables

$s = "Count is (5) 10";
$n = sscanf($s, "%s %s (%d) %d", &$s1, &$s2, &$v1, &$v2);   # 'Count', 'is', 5, 10 and n=4

Output PHP String

Format and print PHP string

print("Some text");                             # True if the print is success otherwise false
printf('%.2f', 234.556);                        # 234.56
printf('Decimal %d Hex %x', 330, 330);          # Decimal 330 Hex 14a
printf('Padding %03d', 5);                      # Padding 005
printf('%02d/%02d/%04d', $month, $day, $year);  # 10/30/2009
printf('%.2f%% (Percent)', 10.1);               # 10.10% (Percent)

$str = sprintf('%.2f', 234.556);                # Output to a string

Print a PHP variable

print_r($a);                                    # Print an object (Better format than echo or print)

Output a PHP variable as a String

print_r($a, 1);

PHP String Comparison

PHP equality comparison

0 == '0';                                        # TRUE
0 === '0';                                       # FALSE: Not of the same type

PHP String comparison

'ab' < 'bf';                                     # TRUE, Do not use this to compare a string with a numeric value

strcmp('ab', 'bf');                              # <0 if smaller, 0 if equal, >0 if greater
strcasecmp('FG', 'fg');                          # Case insensitive comparison

PHP string comparison using natural order

$v1 = 'pupil';
$v2 = 'people';
soundex($v1) == soundex($v2);                    # TRUE if $v1 & $v2 have similar pronunciation
metaphone($v1) == metaphone($v2);                # Same but it use a more accurate comparison algorithm

$common = similar_text($v1, $v2, $percent);      # Calculate how many common characters between 2 strings
                                                 # Percent store the percentage of common chars

$diff = levenshtein($v1, $v2);                   # Compute the difference of 2 text

PHP String Index, Seach & Replace

Find the index location of a PHP sub-string

$pos = strpos("abcd", "cd");                     # 2: return the index of the first match
if ($pos==FALSE) {                               # return false if not found
   echo "NOT FOUND";
}

$pos = strrpos("abcd", "c");                     # return the index of the last match
                                                 # Reverse search does not takes multiple chars

Return a PHP sub-string

substr('0123456789', 4);                         # '456789' (start at index 4)
substr('0123456789', 4, 3);                      # '456' (start at index 4 with length of 3)

$count = substr_count('abcd abfr frab', 'ab');   # 3: 'ab' occurs 3 times
$s = 'John:Paul:Mary';
$r = strstr($s, ":");                            # $r is 'Paul:Mary' After a match, return the rest of string
$r = stristr($s, ":");                           # The match is case in-sensitive

PHP String replacement

$result = substr_replace('hello world', 'hi', 0, 5); # 'hi world': Replace character from index 0 & up to length 5

$result = substr_replace($original, $repl_substring, $start_index, $length);
  • If length is missing, replace until the end of the string
  • If length is 0, insert the string before index n
  • If the replace string is "", it means delete
  • negative index means counting from the end. e.g. -2 means the second last character

PHP Regular Expression

ereg('^Start', 'Start with ...');       # TRUE: string start with "Start"
ereg('end$', "... the end");            # TRUE: string end with "end"
Expression Description
a.c wild card for one single character
[aeiou] Match one of this
[a-zA-Z] Match from a range
[^aeiou] Do not match one of this
apple|orange One of this
(apple)|(orange) Same as above

[0..9]+ means 1 or more digits

Option Description
? 0 or 1
* 0 or more
+ 1 or more
{n} Exactly n times
{n,m} At least n, no more than m times
{n,} At least n

Escape Special Characters Avoiding Cross Script Attacks

Escape HTML characters to be displayed in a HTML page

$r = htmlspecialchars($s)       # Escape Special HTML characters & " ' < >

PHP String function

PHP string length

strlen("text");

PHP string trimming

$r = trim('    text   ');
$r = ltrim('  text');
$r = rtrim('text    ');

$r = trim('    text   ', ' ,.');                 # trim space or ',' or '.'

PHP string reverse

$s = 'abcd';
$r = strrev($s);                                 # Reverse a string

PHP String case manipulation

$r = strtolower($s);                             # Lower case
$r = strtoupper($s);                             # Upper case
$r = ucfirst($s);                                # Upper case the first character
$r = ucwords($s);                                # Upper case the first character of all words

PHP String repeat

$r = str_repeat($s, 3);                          # Repeat $s 3 times

PHP string padding

$r = str_pad('This is a test', 30);              # Pad up to 30 characters with ' '
$r = str_pad('This is a test', 30, '. ');        # Pad up to 30 characters with '. '
$r = str_pad('This is a test', 30, ' ', STR_PAD_RIGHT); # Pad space on the right. (STR_PAD_LEFT, or STR_PAD_BOTH)
PHP String Function Description
addcslashes Quote String containing C Style slashes
addslashes Quote string containing slashes
bin2hex Binary to Hex
chop Trim space off the end
chr Return a character
chunk_split Split a string
convert_uudecode Decode a uuencoded string
convert_uuencode Uuencode a string
count_chars Count characters
crc32 crc32 polynomial of a string
crypt string encryption
echo Output strings
explode Split a string with specific delimiter
fprintf Output a formatted string to a stream
get_html_translation_table Get the HTML translation table
html_entity_decode Convert HTML entities
htmlentities Convert characters to HTML entities
htmlspecialchars_decode Convert special HTML entities to characters
htmlspecialchars Convert special characters to HTML entities
implode Join array elements to a string
join Join array elements to a string
lcfirst Lowercase first character
levenshtein Levenshtein distance between two strings
localeconv Get numeric formatting information
ltrim Left trim
md5_file md5 hash of a file
md5 md5 hash of a string
metaphone metaphone key of a string
money_format Convert to a currency string
nl_langinfo Language and locale information
nl2br Inserts HTML line breaks on all newlines
number_format Format a number
ord ASCII value
parse_str Parses the string into variables
print Output a string
printf Output a formatted string
quoted_printable_decode Convert a string to an 8 bit string
quoted_printable_encode Convert a 8 bit string to a string
quotemeta Quote meta characters
rtrim Right trim
setlocale Set locale
sha1_file sha1 hash of a file
sha1 sha1 hash of a string
similar_text Find the distance between two strings
soundex soundex key of a string
sprintf Return a formatted string
sscanf Parses a string according to a format
str_getcsv Parse a CSV string into an array
str_ireplace str_replace (case insensitive)
str_pad Pad a string
str_repeat Repeat a string
str_replace Replace all occurrences
str_rot13 rot13 transform
str_shuffle shuffle a string
str_split Convert a string to an array
str_word_count Word count
strcasecmp Binary case-insensitive string comparison
strchr First occurance
strcmp String comparison
strcoll Locale based string comparison
strcspn Find length of initial segment not matching mask
strip_tags Strip out HTML and PHP tags
stripcslashes Un-quote string added by addcslashes
stripos Find position of first occurrence (case-insensitive)
stripslashes Un-quotes a quoted string
stristr Case-insensitive strstr
strlen Get length
strnatcasecmp Comparisons using a natural algorithm (case insensitive )
strnatcmp comparisons using a natural algorithm
strncasecmp Binary comparison of the first n characters (case insensitive)
strncmp Binary comparison of the first n characters
strpbrk Search a string for a set of characters
strpos Sub-string position
strrchr Find the last occurrence
strrev Reverse
strripos Find position of last occurrence (case-insensitive)
strrpos Find position of last occurrence
strspn Find first segment
strstr First occurrence
strtok Tokenize string
strtolower Lowercase
strtoupper Uppercase
strtr Translate characters
substr_compare Substring comparison
substr_count Count the occurrence of substring
substr_replace Replace sub-string
substr SubString
trim Trim whitespace
ucfirst Uppercase first character
ucwords Uppercase the first character of every words
vfprintf Formatted string to a stream
vprintf Output a formatted string
vsprintf Format string
wordwrap Wraps a string