How to Extract Substring from a String in PHP?
Given a String, the task is to extract substring from string in PHP. Extracting substrings from a string is a common task in PHP, whether you need to extract a portion of text based on a specific position or find a substring based on a pattern. In this article, we will explore various approaches to extract substrings from a string in PHP.
Table of Content
- Using substr() Function
- Extracting Substring Before a Specific Character
- Using Regular Expressions (Regex)
Approach 1: Using substr() Function
The substr() function is used to extract a substring from a string in PHP. It takes three arguments: the input string, the starting position (zero-based index), and optionally the length of the substring to extract.
<?php
$str = "Welcome to w3wiki";
$subStr = substr($str, 11, 13);
echo $subStr;
?>
Output
w3wiki
Approach 2: Extracting Substring Before a Specific Character
To extract a substring that appears before a specific character or substring, you can use the strstr() function.
<?php
$str = "Welcome to w3wiki";
$subStr = strstr($str, 'G');
echo $subStr;
?>
Output
w3wiki
Approach 3: Using Regular Expressions (Regex)
Regex provides a powerful way to extract substrings based on patterns. The preg_match() function can be used to extract substrings that match a specific regex pattern.
<?php
$str = "Welcome to w3wiki - A computer science portal";
if (preg_match('/to (.*?) -/', $str, $matches)) {
echo $matches[1];
}
?>
Output
w3wiki