This document provides an overview of strings in PHP. It discusses single and double quote strings and how they differ in handling escape sequences and variable interpolation. It also covers the heredoc syntax. The document explains functions for comparing, manipulating, and extracting substrings from strings. These include strcmp(), strlen(), substr(), and regular expression functions. It provides examples of escaping characters, accessing strings as arrays, and using strings with functions like number_format(). Overall, the document is a guide to the basics of strings and common string functions in PHP.
3. String basics
1. Single quote strings (‘ ’)
– single quotes represent ‚simple strings,‛ where almost all characters are
used literally
2. Double quote strings(‚ ‛)
– complex strings‛ that allow for special escape sequences (for example, to
insert special characters) and for variable substitution
$a=‚Baabtra‛;
echo ‘Hello $a’;
echo ‚Hello $a n welcome‛;
Hello $a
Hello baabtra
welcome
Out put
4. String basics - contd
• Clearly, this ‚simple‛ syntax won’t work in those situations in which the
name of the variable you want to interpolated is positioned in such a way
inside the string that the parser wouldn’t be able to parse its name in the
way you intend it to. In these cases, you can encapsulate the variable’s name
in braces
$me = ’Davey’;
$names = array (’Smith’, ’Jones’, ’Jackson’);
echo "There cannot be more than two {$me}s!";
echo "Citation: {$names[1]}[1987]";
5. String basics - contd
3. The Heredoc Syntax
used to declare complex strings, the functionality it provides is similar to double
quotes, with the exception that, because heredoc uses a special set of tokens to
encapsulate the string, it’s easier to declare strings that include many double-
quote characters.
$who = "World";
echo <<<TEXT
So I said, "Hello $who"
TEXT;
6. Escaping Literal Values
• All three string-definition syntax feature a set of several characters
that require escaping in order to be interpreted as literals.
echo ’This is ’my’ string’;
$a = 10;
echo "The value of $a is "$a".";
echo "Here’s an escaped backslash:";
7. String as arrays
• You can access the individual characters of a string as if they were
members of an array
$string = ’abcdef’;
echo $string[1]; // Outputs ’b’
}
8. String comparison == and ===
$string = ’123aa’;
if ($string == 123) {
// The string equals 123
}
• You’d expect this comparison to return false, since the two operands are not the
same. However, PHP first transparently converts the contents of $string to the
integer 123, thus making the comparison true.
• Naturally, the best way to avoid this problem is to use the identity operator ===
10. String functions –strcmp(), strcasecmp()
strcmp(), strcasecmp() both returns zero if the two strings passed to the
function are equal. These are identical, with the exception that the former is
case-sensitive, while the latter is not.
$str = "Hello World";
if (strcmp($str, "hello world") === 0) {
// We won’t get here, because of case sensitivity
}
if (strcasecmp($str, "hello world") === 0) {
// We will get here, because strcasecmp() is case-insensitive
}
11. String functions –strcasencmp()
strcasencmp() allows you to only test a given number of characters
inside two strings.
$s1 = ’abcd1234’;
$s2 = ’abcd5678’;
// Compare the first four characters
echo strcasencmp ($s1, $s2, 4);
13. String functions –strtr()
strtr() used to translate certain characters of a string into other
characters
• Single character version
echo strstr (’abc’, ’a’, ’1’);
• Multiple-character version
$subst = array (’1’ => ’one’,’2’ => ’two’);
echo strtr (’123’, $subst);
1bc
Out put
onetwo3
Out put
14. String functions –strpos()
• strpos() allows you to find the position of a substring inside a string. It
returns either the numeric position of the substring’s first occurrence within
the string, or false if a match could not be found.
• You can also specify an optional third parameter to strpos() to indicate that you
want the search to start from a specific position within the haystack.
$haystack = ’123456123456’;
$needle = ’123’;
echo strpos ($haystack, $needle);
echo strpos ($haystack, $needle, 1);
0
Out put
6
15. String functions –stripos() , strrpos()
• stripos() is case-insensitive version of strpos()
echo stripos(’Hello World’, ’hello’);
• Strpos() does the same as strpos(), but in the revers order
echo strrpos (’123123’, ’123’);
0
Out put
3
Out put
16. String functions –strstr()
• The strstr() function works similarly to strpos() in that it searches the main
string for a substring. The only real difference is that this function returns the
portion of the main string that starts with the sub string instead of the latter’s
position:
$haystack = ’123456’;
$needle = ’34’;
echo strstr ($haystack, $needle);
3456
Out put
17. String functions –stristr()
• stristr() is case-insensitive version of strstr()
echo stristr(’Hello My World’, ’my’); My World
Out put
18. String functions –str_replace(), str_ireplace()
• str_replace() used to replace portions of a string with a different substring
echo str_replace("World", "Reader", "Hello World");
• Str_ireplace() is the case insensitive version of str_replace()
echo str_ireplace("world", "Reader", "Hello World");
• Optionally, you can specify a third parameter, that the function fills, upon
return, with the number of substitutions made:
$a = 0;
str_replace (’a’, ’b’, ’a1a1a1’, $a);
echo $a;
Hello Reader
Out put
Hello Reader
Out put
3
19. String functions –str_replace(), str_ireplace()
• If you need to search and replace more than one needle at a time, you can pass the first
two arguments to str_replace() in the form of arrays
• echo str_replace(array("Hello", "World"), array("Bonjour", "Monde"), "HelloWorld");
• echo str_replace(array("Hello", "World"), "Bye", "Hello World");
Bye Bye
Hello Reader
20. String functions –substr()
• The very flexible and powerful substr() function allows you to extract
a substring from a larger string.
echo substr ($x, 0, 3); outputs 123
echo substr ($x, 1, 1); outputs 2
echo substr ($x, -2); outputs 67
echo substr ($x, 1); outputs 234567
echo substr ($x, -2, 1); outputs 6
21. String functions –number_format()
• Number formatting is typically used when you wish to output a
number and separate its digits into thousands and decimal points
• echo number_format("100000.698‚ , 3 , "," , ‚ ");
100 000,698
Number to be formatted
Number of decimal places to be rouned
decimal separator
Thousand separator
Output
23. Regular Expressions
• Perl Compatible Regular Expressions (normally abbreviated as
‚PCRE‛) offer a very powerful string-matching and replacement
mechanism that far surpasses anything we have examined so far.
• The real power of regular expressions comes into play when you
don’t know the exact string that you want to match
24. Regular Expressions - Delimiters
• A regular expression is always delimited by a starting and ending
character.
• Any character can be used for this purpose (as long as the
beginning and ending delimiter match); since any occurrence of
this character inside the expression itself must be escaped, it’s
usually a good idea to pick a delimiter that isn’t likely to appear
inside the expression.
25. Regular Expressions – Meta characters
• However, every metacharacter represents a single character in the
matched expression.
. (dot)Match any character
ˆ Match the start of the string
$ Match the end of the string
s Match any whitespace character
d Match any digit
w Match any ‚word‛ character
26. Regular Expressions – Meta characters
• Meta characters can also be expressed using grouping expressions. For example, a
series of valid alternatives for a character can be provided by using square brackets:
/ab[cd]e/
• You can also use other metacharacters, and provide ranges of valid characters inside a
grouping expression:
/ab[c-ed]/
The expression will match abce or abde
This will match abc, abd, abe and any combination
of ab followed by a digit.
27. Regular Expressions – Quanitifiers
• This will match abc, abd, abe and any combination of ab followed by a digit.
* The character can appear zero or more times
+ The character can appear one or more times
? The character can appear zero or one times
{n,m} The character can appear at least n times, and no more than m.
Either parameter can be omitted to indicated a minimum limit
with nomaximum, or a maximum limit without aminimum,
but not both.
ab?c matches both ac and abc,
ab{1,3}c matches abc, abbc and abbbc.
Example
28. Regular Expressions – Sub-Expressions
• A sub-expression is a regular expression contained within the
main regular expression (or another sub-expression); you define
one by encapsulating it in parentheses:
/a(bc.)e/
/a(bc.)+e/
Example
29. Matching and Extracting Strings
• The preg_match() function can be used to match a regular
expression against a given string.
$name = "Davey Shafik";
// Simple match
$regex = "/[a-zA-Zs]/";
if (preg_match($regex, $name)) {
// Valid Name
}
Example
32. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
33. Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com