5 important string functions in PHP

9:57 AM 0 Comments

1. ucfirst()

ucfirst() makes the first letter of the word in UPPERCASE. This function is going to be very useful to display names on your website. 

<?php

$str = "john";
echo ucfirst($str);
?>

The output will be like
John

2. strlen()

strlen() return the length of the string. 

This function return the number of characters in the string including white space, or returns 0 if the string is empty.

<?php
$name 
'John';
echo 
strlen($name); // 4$name ' Jo hn ';
echo 
strlen($name); // 7?>

3. strtolower()

strtolower() converts the entire characters in the string to lowercase. This function is going to be useful for you when you have to display email addresses or website links on your webpages. 

Example program:

We are going to see an example to convert an improper email id to proper form.

<?php
$str 
"MisterX@Gmail.Com";$str strtolower($str);
echo 
$str
?>

The output will be like :
 misterx@gmail.com

4. strtoupper()

strtolower() converts the entire characters in the string to uppercase. This function is going to be useful when you have to display headings on your webpage.

<?php
$str 
"artificial intelligence";$str strtoupper($str);
echo 
$str
?>
The output will be;
ARTIFICIAL INTELLIGENCE

5. substr()

substr() returns a part of the given string.

Syntax: substr( string, starting-position, length );

String: The string in which a selected part is going to get extracted.
Starting-Position: A positive or negative integer value determines the position of the starting character of the sub string.
Length: The length of the sub-string going to get extracted. 

The position of the characters can be mentioned as Positive values as well as Negative values. Positive values specifies the position from the starting of the string, and Negative values specifies the position of the characters from the end of the string.

Example: 

Positive values: 
Value
1
2
3
4
5
6
7
8
9
10
11
String
h
e
l
l
o

w
o
r
l
d
Negative values:
Value
-11
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
String
h
e
l
l
o

w
o
r
l
d

Example programs:
Here in this example we are going to extract a second lever domain and the top-level domain of a website.

www.lamewishes.com

Extracting the second lever domain:
<?php 
$str = "www.lamewishes.com";
echo substr($str, 4, 10);
// lamewishes

?>
Extracting the top-lever domain:
<?php 
$str = "www.lamewishes.com";
echo substr($str, -3);
// com

?>
Extracting the domain name
<?php 
$str = "www.lamewishes.com";
echo substr($str, 4);
// lamewishes.com

?>

If we do not mention the length of the sub-string the function returns the string form the starting point to the rest of the string.

Jefinson O

I'm a PHP developer, I'm so interested to share something with people what I learn today. Blogging is my Hobby and I love doing it. Google

0 comments: