String - potatoscript/php GitHub Wiki
Strings in PHP
Overview
A string in PHP is a sequence of characters that can include letters, numbers, and symbols. Strings are one of the most commonly used data types in PHP for handling text-based data such as user input, file content, or HTML output.
In this section, we will cover the following topics:
- What is a String?
- String Creation
- String Concatenation
- String Length
- String Functions
- Searching and Replacing Strings
- String Formatting
What is a String?
A string is a series of characters enclosed in quotes. PHP allows you to use both single quotes ('
) and double quotes ("
) for defining strings, each with its own behavior.
Example:
<?php
$string1 = "Hello, World!";
$string2 = 'Hello, PHP!';
echo $string1; // Outputs: Hello, World!
echo $string2; // Outputs: Hello, PHP!
?>
Explanation:
$string1
uses double quotes, and$string2
uses single quotes. Both represent valid strings in PHP.
String Creation
You can create strings using both single and double quotes. Each has its own behavior:
- Single quotes: Characters within single quotes are treated literally, with no special parsing (except for escape sequences like
\\
and\'
). - Double quotes: Variables within double quotes are parsed and replaced with their values.
Example (Single Quotes):
<?php
$name = "Lucy";
echo 'Hello, $name!'; // Outputs: Hello, $name! (Variable is not parsed)
?>
Example (Double Quotes):
<?php
$name = "Lucy";
echo "Hello, $name!"; // Outputs: Hello, Lucy! (Variable is parsed)
?>
Explanation:
- In the first example, single quotes do not parse the
$name
variable. - In the second example, double quotes allow the
$name
variable to be parsed and its value to be inserted into the string.
String Concatenation
In PHP, you can combine two or more strings using the concatenation operator (.
).
Example:
<?php
$firstName = "Lucy";
$lastName = "Berry";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: Lucy Berry
?>
Explanation:
$firstName
and$lastName
are combined into a single string with a space in between using the.
operator.
String Length
To find the length of a string, you can use the strlen()
function. This function returns the number of characters in a string.
Example:
<?php
$text = "Hello, World!";
echo strlen($text); // Outputs: 13
?>
Explanation:
strlen()
counts the number of characters in the string$text
, including spaces and punctuation.
String Functions
PHP provides a wide variety of functions for manipulating strings. These functions allow you to perform tasks such as modifying case, trimming whitespace, and more.
Common String Functions:
strtoupper()
: Converts a string to uppercase.strtolower()
: Converts a string to lowercase.ucwords()
: Capitalizes the first letter of each word in a string.substr()
: Extracts a portion of a string.trim()
: Removes whitespace from both ends of a string.
Examples:
<?php
$text = " Hello, PHP! ";
// Convert to uppercase
echo strtoupper($text); // Outputs: HELLO, PHP!
// Convert to lowercase
echo strtolower($text); // Outputs: hello, php!
// Capitalize first letter of each word
echo ucwords($text); // Outputs: Hello, Php!
// Extract substring
echo substr($text, 7, 3); // Outputs: PHP
// Trim whitespace
echo trim($text); // Outputs: Hello, PHP!
?>
Explanation:
strtoupper()
converts all characters to uppercase.strtolower()
converts all characters to lowercase.ucwords()
capitalizes the first letter of each word in a string.substr()
extracts a substring starting at position 7 and for a length of 3 characters.trim()
removes leading and trailing whitespace.
Searching and Replacing Strings
PHP provides functions to search for specific substrings within strings and replace them if necessary.
Example (Searching):
<?php
$text = "Hello, PHP World!";
$position = strpos($text, "PHP"); // Finds the position of "PHP"
echo $position; // Outputs: 7 (position of "PHP")
?>
Example (Replacing):
<?php
$text = "Hello, World!";
$newText = str_replace("World", "PHP", $text); // Replaces "World" with "PHP"
echo $newText; // Outputs: Hello, PHP!
?>
Explanation:
strpos()
returns the position of the first occurrence of a substring ("PHP") in the string.str_replace()
replaces all occurrences of a substring ("World") with another substring ("PHP").
String Formatting
You can format strings using sprintf()
or printf()
. These functions allow you to insert variables into strings in a specified format.
Example (sprintf):
<?php
$name = "Lucy";
$age = 30;
$formattedString = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $formattedString; // Outputs: My name is Lucy and I am 30 years old.
?>
Example (printf):
<?php
$name = "Lucy";
$age = 30;
printf("My name is %s and I am %d years old.", $name, $age); // Outputs: My name is Lucy and I am 30 years old.
?>
Explanation:
sprintf()
returns a formatted string, whileprintf()
directly outputs it.- The placeholders
%s
and%d
are replaced by the variables$name
and$age
.
Conclusion
In this section, we covered the following topics:
- String Creation: How to create strings using single and double quotes.
- String Concatenation: Combining strings using the
.
operator. - String Length: Using
strlen()
to get the length of a string. - String Functions: A variety of functions for manipulating strings, such as
strtoupper()
,substr()
, andtrim()
. - Searching and Replacing Strings: Finding and replacing substrings using
strpos()
andstr_replace()
. - String Formatting: Formatting strings using
sprintf()
andprintf()
.
Strings are an essential part of PHP programming, and mastering them will enable you to handle text data effectively. In the next section, we will explore Working with Forms in PHP, which is crucial for handling user input and submitting data to the server.
- Line Breaks :
echo nl2br('This is an Example \n line');
- Remove all whitespace :
$str = preg_replace('/\s+/','',$str);
- Search Character
- Split String
- String Length :
strlen($string);
- String to lowercase :
strtolower("ABC") => abc
- String to uppercase :
strtoupper("abc") => ABC
- strpos :
substr($name,strpos($name,'.')+1);
- SubString
Search-Character
$String1 = "abcdefg";
$String2 = "BCD";
if(!strstr($String1, $String2)){
echo "not found";
}else{
echo "found";
}//output => not found -> by using strstr uppercase and lowercase was concerned
$String1 = "abcdefg";
$String2 = "BCD";
if(!stristr($String1, $String2)){
echo "not found";
}else{
echo "found";
}//output => found -> by using stristr
Split-String
- explode("-",$string);
$string = "RR6008A-000";
$str = explode("-",$string);
$s = $str[0]."-".substr($str[1],0,2); => RR6008A-00
SubString
$string = "abc-123-999";
substr($string,4); => 123-999
substr($string,0,3); => abc
substr($string,-3); => 999 //take the last 3 char
substr($string,4,3); => 123