Built-In String Functions in PHP
Built-In String Functions in PHP
• Functions:
• strlen(): Returns the length of a string.
• Example: strlen("hello world") returns 11.
• Use Case: Validating user input length, such as passwords or
usernames.
• trim(), ltrim(), rtrim(): Remove whitespace from the
beginning (ltrim), end (rtrim), or both ends (trim) of a
string.
• Example: trim(" hello world ") results in "hello world".
• Use Case: Cleaning up input data before processing or
storage.
Extracting and Splitting Substrings
• Functions:
• substr(): Returns a portion of a string starting from a specified position
and length.
• Example: substr("hello world", 0, 5) returns "hello".
• Use Case: Extracting specific parts of strings, such as file names from a
path.
• str_split(): Splits a string into an array of characters.
• Example: str_split("hello") returns ["h", "e", "l", "l", "o"].
• Use Case: Analyzing or manipulating individual characters in a string.
• explode(): Splits a string into an array based on a delimiter.
• Example: explode(" ", "hello world") returns ["hello", "world"].
• Use Case: Breaking a sentence into words or splitting CSV data.
• implode(): Joins array elements into a string with a specified delimiter.
• Example: implode("-", ["hello", "world"]) returns "hello-world".
• Use Case: Creating a string from array data, such as generating slugs or
paths.
Formatting and Padding
• Functions:
• sprintf(): Returns a formatted string based on a format
specification.
• Example: sprintf("%s is %d years old", "John", 25)
returns "John is 25 years old".
• Use Case: Formatting strings for consistent display, such as
outputting dates and numbers.
• printf(): Outputs a formatted string directly.
• Example: printf("Hello %s", "World") displays "Hello
World".
• Use Case: Displaying formatted output without needing to
assign it to a variable.
• str_pad(): Pads a string to a certain length with another string.
• Example: str_pad("Hello", 10, "-") returns "Hello-----".
• Use Case: Ensuring consistent string lengths in user interfaces
or reports.
Encoding and Escaping Strings
• Functions:
• htmlspecialchars(): Converts special characters to HTML
entities.
• Example:
htmlspecialchars("<script>alert('XSS');</script>") returns
"<script>alert('XSS');</script>".
• Use Case: Preventing XSS (cross-site scripting) attacks by
escaping user-generated content.
• htmlentities(): Converts all applicable characters to HTML
entities.
• Example: htmlentities("©") returns "©".
• Use Case: Ensuring that special characters display correctly in
HTML.
• addslashes(): Adds backslashes before special characters like
quotes.
• Example: addslashes("O'Reilly") returns "O\'Reilly".
• Use Case: Escaping input data before inserting it into a database
to prevent SQL injection.