0 ratings0% found this document useful (0 votes) 43 views14 pagesStrings in PHP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
J
serings are character sequences that can be processed as a unit by assigning them to variables,
ing them as input to functions, returning them from functions, or transmitting therm as output
sisplay on your user’s web page. In PHP code, the simplest approach to specify @ string is to
it in quotation marks, whether single quotation marks (°) or double quotation marks ("), a
ywn below:
] WHAT IS STRING?
smy_string = ‘A literal string’;_~
sanother_string = “Another string”.
‘The distinction between single and double quotation marks is based on how much PHP
Jates the characters between the quote signs before producing the string itself. When a string
‘closed in single quotation marks, almost no interpolation is performed; when it is enclosed in
Je quotation marks, PHP will splice in the values of any variables you include, as well as make
‘tutions for certain special character sequences that begin with the backslash () character.
For example, consider evaluating the following code in the center of a web page:
Sstatement = ‘everything I say’;
Squestion_1 = “Do you have to take Sstatement so literally?\n
”;
Squestion_2 = ‘Do you have to take Sstatement so literally?\n
’;
echo Squestion_1;
echo Squestion_2;
should expect to see the browser output:
Do you have to take everything I say so literally?
Do you have to take Sstatement so literally?\n,
PHP &
LE
can be created and declared in PHP using single quotes () or double quotes ("). The
inct syntaxes for building multi-line texts, such as heredoc and nowdoc. In PHP, ya
and define strings as follows
1. Single-Quoted Strings:
Single-quoted strings are simple and straightforward. The content within single quotes ,
treated literally, and escape sequences are not interpreted.
Example:
SsingiXQuotedString = ‘This is a single-quoted string.’;
2. Double-Quoted Strings:
Double-quoted strings allow for the inclusion of variables and the interpretation of escap
sequences, This makes them more versatile than single-quoted strings.
Example:
Svariable = ‘PHP’;
SdoubleQuotedString = “This is a double-quoted string with a
Svariable variable.”;
Example: To illustrate the single-quoted and double-quoted string in PHP.
1] Workable names instén » single-qoted string Tete Seeee
[Thay hl oe treated oa repilar tert, not the value of the
nas Tonal eed ig vi cpl eee
Ths doble goed snag wi “escape” care
-quited string
119 All replace the variable sth its value.
cho “Hallo, texsmple!”;
che * co07";
[tscaping characters wd sgactal characters in PP quotes:
ingle = “This is a single-quated string with
actersLL
ings in CHP
Concatenation:
You can concatenate strings using the . (dot) operator
peample:
sfirstName = ‘John’;
siastName = ‘Doe’;
sfullName = SfirstName . ‘>. SlastName;
gsomple: To Mustrate the string cot itenation in PHP. i aa saa
er Se ee eet
6. Nowdoc:
‘Nowdoc is similar to heredoc but treats the content as a literal string, not evaluating variables
or escape sequences. It starts with ‘<<<' followed by a label and ends with the same label.
Example:
SnowdocString = <<<‘EOD?
This is a nowdoc string.
It behaves like a single-quoted string.
EOD;ms
Mahith I love PEP.
Sname I love PHP.
redec @
1e me
ye <<<€0T Pl]
ec
name 15 Shame
Bove PHP.
cote
3
cho “
"5
a
No" mp I
Vino <<<°EOT
come ie Sue
MY oe PHP. *
Bors
|
se I
Special Characters in Double-Quoted Strings:
Double-quoted strings allow for the inclusion of variables and special characters.
For example, you can use \ to escape characters:
Svariable = ‘PHP’;
SspecialString = “This is a double-quoted string with a variable: \Svar
te cleaner, multi-line strings.
STRING FUNCTIONS
PHP provides an abundance of functions for string consumption and crunching. If you're
pted to write your function that reads strings character by character to generate a new string,
¢ a minute to consider whether the task is frequent. If this is the case, there is most likely a
ilt-in function that handles it.
ote: A word of caution for C programmers: Many of the names of PHP string functions should
familiar to you. Remember that because PHP handles memory for you, functions that return
ings allocate string storage on their own and do not need a preallocated string to write into.
String Length: e
i i ser.
> strien(): Takes a single string argument and returns-the length of the string as an integerrue a sy,
Sshort_string = “This string has 29 characters”;
print(“It does have “. strien(Sshort_string) . “ characters”);
This code gives the following output
It does have 29 characters
Knowing the length of a string is especially useful in form validation and scenariog
we want to loop through a string character by character. Using the preceding, exam
string, is:
for (Sindex = 0; Sindex < strlen(Sshort_string); Sindex++)
print(Sshort_string{Sindex});
This simply prints
This string has 29 characters which is the string we started with
Finds the numerical position of a particular character in a string,
icked a peck of pickled peppers”; "
‘p’) ’
’);
strpos() :
Stwister = “Peter Piper
print(“Location of ‘p’
” . strpos(Stwister,
” , strpos(Stwister, ‘q’)
’); y,
S geeuce™
.
|
Location of ‘p’ is 8 Ho Che é
Location of “q’ is
The ‘q’ location is apparently blank because strpos() returns false if the character jy
question cannot be found, and a false value prints as the empty string. You should not,
print(“Location of ‘q’ is
This gives us the browser output: 4
that the strpos() function is case sensitive.
By passing it a multicharacter string rather than a single-character string, the strpos)
method can be used to search for a substring rather than a single character. You ca,
optionally provide an extra integer input setting the point to start searching from. The
strrpos() function can also be used to search in reverse.
strrpos(): Searching in reverse is also possible, using the strrpos() function. This function
takes a string to search and a single-character string to locate, ‘and it returns |
position of occurrence of the second argument in the first argument. (Unlike with strpos(),
the string searched for must have only one character.) If we use this function on ow
example sentence, we find a different position:
Stwister = “Peter Piper picked a peck of pickled peppers”;
print{(“Location of ‘p’ is”. strrpos(Stwister, ‘p’)
’);
Specifically, we find the third p in TS: 4a
Pp y, p in pepper f oceurrene 9
Location of ‘p’ is 40 “bso afro es
‘ nde tee. sitio a nother Shy (oxo
Ps dn Pods ing trae @ ;gn 7
ample: Illustrate the string length function in PHP.
16
strempQ: Takes two strings as arguments and returns 0 if the strings are exactly
equivalent. If stremp() encounters a difference, it returns a negative number if the first
different byte is a smaller ASCII value in the first string, and a positive number if the
smaller byte is found in the second string.
Example:
Sstrl = “Hello”;
$str2 = “Hello”; Ree)
Sresult = stremp(Sstrl, $str2); // Returns 0 (if equal)
> streasecmp():Identical to stremp(,|exe
same letter compare as equal. fev
Example:
| Sstr1 = “Hello”;
$str2 = “hello”; hy
that lowercase and uppercase yersions of the
Be Cem ih ve
Sresult = strcasecmp(Sstrl, $str2); // Returns 0 (ifequal)
> strstr() : Searches its first string argument to see if. its second string argument is contained
in it, Returns the substring of the first string that starts with the first instance of the second
argument, if any is found — otherwise, it returns false.
Sstring_to_search = “showsuppnceshowsuptwice”;
Sstring to find=“up?;
print(“Result of looking for $string _to_find” .
strstr(Sstring_to_search, Sstring_to_find) . “
”);ee 2: ee
Sstring_to_find = “down’
print(“Result of looking for Sstring_to_find” .
strstr(Sstring_to_search, Sstring_to_find));
which gives us:
Result of looking for up: uponceshowsuptwice => } +
Result of looking for down )
Examples:
1, Illustrate the string comparison function in PHP.
| *; I
/ (Compare two strings (case-sensitive):
echo stromp("Hello world!","hello world!");
echo “
"; i!
/(Compare two strings (case-insensitive):
echo strncasecmp("Hello”,"hELLO”,2);
echo “";
//The strstr() function searches for the first occurrence of a string
inside another string.
echo strstr("Hello world!”,"world"); i
32
world!
2. Illustrate the string searching function in PHP.
';
$search2 = “php”; //case-sensitive
var_dump(strstr($string, $search2)); |
echo ""; \
var_dump(strstr($string, “WelcOmE”)) ;
2 |
PHP world!
bool(false)
e bool(false)fee
” ”
& ing Selection: ice
# : Many of PHp
abst) of PHP's
f wt tring fine
” py vege choosing pore, 278 1 do with sci and dicing 7 >
moot ofa setentive!
vet igo a, ew
ihe or18iNal ATBUMENL intacy, USAlly, such Functions return a modified copy. leavin
re substr() method, which
a ara a eng tte pi
the substring will be ch ie ® section of a string. It accepts a string (from which
pegins). and aN optional third inne n Be (the location at which the desired substring
sobetting Oa isto third parame Bument that specifies the length of the desired
(Keep i mind that, ike al PHP argue stings assumed to continue until the end
umbering Pegins with 0 rather than 1 ) ts dealing with numerical string positions, the
our strings
example:
sstr = “Hello, Wortar;
ssubstring = substr(Sstr, 0,5); // Returns “Hetlo
function selects A ello’
ae asdaneag eae by numerical poston, srs slets a substring PY
lumerical position of a given substring.
In the case where we're sure in adi ‘ oF
scontained as a substring, the e oe that the string $containing has the string
strstr(Scontaining, Scontained)
should be equivalent to the code:
substr(Scontaining, strpos(Scontaining, Scontained)) |
__ wring Cleanup Funetions:
‘he functions chopQ, Itrim(), and trim( are really used for cleaning up untidy strings. They
an wbitespace off the end, the beginning, and the beginning and end, respectively, of their single
sng argument.
some examples:
Soriginal = “ More than meets the eye “;
Schopped = chop(Soriginal);
Sitrimmed = Itrim(Soriginal);
$trimmed = trim(Soriginal);
print(“The original is ‘Soriginal’
”);
print(“Its length is “ . strlen(Soriginal) . “
”);
print(“The chopped version is ‘Schopped’
”);
print(“Its length is “ . strlen(Schopped) . “
”);
"a4’
”)5
«
”)s
print(“The Itrimmed version is “$itrimme
Print(“Its length is “ . strien(Sitrimmed) » id
Print(“The trimmed version is “sitrimmed’”);
print(“Its length is“. strlen(Strimmed) - "
echo chop($string,
echo “
"3
$string = Welcome to PHP;
echo ltrim($string1);
echo "
";
$string2 = “!! (( !!)) Welcome to PH
7/ The characters '!", "(, ")', ' ' have been specified to
remove from the beginning of the string
echo ltrim($string2, "! ()"); |
echo "
";
$string3 =" Welcome to PHP .
echo trim($string3);
tS pe eee SO ee) eeit
7 peplacement -
oo eplace() funct
«re ion enables you 4
o eemate stri 0 rep 5
sueemnate string. It takes th lace all instances
a i ; of with
ce it with when i Tee arguments: the a particular substring
replace tis found, and the String to be searched for, the string '0
f striny
ror example: '8 (© perform the replacement on
sfirst_edition =
«parma is
imilar to Rhodesia in at least on,
cond_edition fe way.”;
=str Cr
ss tr_replace( Rhodesia”, “Zimbabwe”,
sfirst_edition);
(nird_edition = str_replace(« oe
” x Burma”, “Myanmar”,
ssecond_edition);
print(Sthird_edition);
gives us:
Myanmar is similar to Zimbabwe in at least one way.
This replacement will happen for all instances found of the search string. If our outdated
encyclopedia could be snarfed into a single PHP string, we could update it in one pass.
y_ substr_replace() chooses a portion to replace by its absolute position. The function takes
up to four arguments: the string to perform the replacement on, the string to replace it
with,the starting position for the replacement, and (optionally) the length of the section to
be replaced.
For example:
print(substr_replace(“ABCDEFG”, «4, 2, 3))5
gives us:
AB-FG
The CDE portion of the string has been replaced with the single notice that you are
allowed to replace a substring with a string of a different length. If the length argument is
omitted, it is assumed that you want to replace the entire portion of the string after the
start position.
The substr_replace() function also takes negative arguments for starting position and
length, which are treated exactly the same way as in the substr() function (described in
the earlier section “Substring selection”). It is important to remember with both
str_replace and substr_replace that the original string remains unchanged by these
operations.Lip
tion in PHP,
Example: Ilustrate the string replacement func
php pe) aie
Input
$str
string very da
“You eat fruits, vegetables, nuts every day
Array containing search string by anes)
Ssearchval = array("fruits”, "vegetables", :
rch strin
Array containing replace string from search string
Sreplaceval - array("dosa”, “idly”, “upma”);
Function to replace strinj
rhat getraePlace($searchval, $replaceval, $str);
Print_r($res),
eche Fors"
(use the substr Feplace() function with $length set to @.
In this case, Snsertion with occur. No replacement will take
Place
echo substr_replace( "Hello World?" ,
"PHP", 6, @);
6. String Case:
> Strtolower(): Converts a String to lowercase.
Example:
Sstr = “Hello, World!”;
Slowercase = trtolower(Sstr); // Returns “hello, world!”
> — strtoupper;
Onverts a string to uppercase.
Example:
Sstr = “Hello, World!”;
Suppercase = strtoupper(Sstr);
> uefirstQ: function|
Example:
(/ Returns “HELLO,WORLD!”
capitalizes only the first letter of a string:
hich pronunciation depends on captain!
echo(ucfirst(Soriginal));
D>
> uewords(): function|capitalizes the first letter,of each wal a string:
Example:
";
string after converting first character
esstr = ucwords ($str2); Of every word to uppercase
pint.r(SresSte); i}
»
1. Padding:
» str_pad(): Pad a string to a certain length with another string.
Example:
Sstr = “Hello”;
SpaddedStr = str_pad(Sstr, 10, “-”); // Returns “Hello—”
4. Exploding and Implode:
>» explode(): Splits a string into an array.
Example:
Sstr = “apple,banana,orange”;
Sfruits = explode(“,”, $str);
// Returns array(“apple”, “banana”, “orange”)104
implode(Q): Joins array elements into a string.
Example:
Sfruits = array(“apple”, “banana”, “orange”);
S$str = implode(“, ”, $fruits);
// Returns “apple, banana, orange”
Answer the following questions.
1. What is string?
2. Define concatenation.
3. What is heredoc?
4. What is nowdoc?
5. What is string function?
6. What is explode() in php?
7. What is implode() in php?
Answer the following questions.
1. Explain the string case with example.
2. Explain the string replacement.
3. Explain the substring selection.
4. Explain comparison and searching.
5. Briefly explain the string function with example.
6. How to create and declare a string? Explain with example.
tO