PHP substr() Function: Syntax, Parameters, Return Values, and Practical Usage Examples
This article explains PHP's substr() function, covering its syntax, parameters, return values, and provides multiple code examples demonstrating how to extract, replace, and change the case of substrings; it also discusses handling of negative start positions and optional length arguments.
substr() Function Syntax
The substr() function is a commonly used PHP function for extracting a portion of a string based on a specified start position and length.
<code>substr(string $string, int $start, int $length = null): string|false</code>Parameter Description
$string : The string to be sliced.
$start : The start position; if negative, counting starts from the end of the string.
$length : Optional length of the slice; if omitted, the function extracts from the start position to the end of the string.
Return Value
On success, returns the extracted substring.
On failure, returns false .
Usage of substr()
1. Extract a Part of a String
Example of extracting the word "World" from a string:
<code>$str = "Hello, World!";<br/>$substring = substr($str, 7, 5);<br/>echo $substring; // Output: World</code>In this example, the start position is 7 (the 8th character) and the length is 5, resulting in the substring "World".
2. Extract and Replace a Substring
Extract a substring and replace it with another value, such as changing "World" to "PHP":
<code>$str = "Hello, World!";<br/>$substring = substr($str, 7, 5);<br/>$newStr = str_replace($substring, "PHP", $str);<br/>echo $newStr; // Output: Hello, PHP!</code>The code first extracts "World" using substr() , then replaces it with "PHP" using str_replace() .
3. Extract and Change Case
Extract a substring and convert it to uppercase (or lowercase) before reinserting it:
<code>$str = "Hello, World!";<br/>$substring = substr($str, 7, 5);<br/>$uppercase = strtoupper($substring);<br/>$newStr = str_replace($substring, $uppercase, $str);<br/>echo $newStr; // Output: Hello, WORLD!</code>This example extracts "World", converts it to uppercase with strtoupper() , and then replaces the original substring using str_replace() .
Summary
The substr() function is a versatile PHP tool for string manipulation, allowing developers to extract, replace, or change the case of substrings based on start position and length, with support for negative indices and optional length parameters.
Recommended PHP Learning Resources
Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Recommended Course
Workerman+TP6 Real‑time Chat System (Limited Time Offer)
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.