How to Extract Substring from a String in PHP? Last Updated : 22 Jul, 2024 Comments Improve Suggest changes Like Article Like Report Given a String, the task is to extract a substring from a 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 extracting substrings from a string in PHP.Table of ContentUsing substr() FunctionExtracting Substring Before a Specific CharacterUsing Regular Expressions (Regex)Using explode() FunctionUsing mb_substr() FunctionApproach 1: Using substr() FunctionThe 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 <?php $str = "Welcome to GeeksforGeeks"; $subStr = substr($str, 11, 13); echo $subStr; ?> OutputGeeksforGeeksApproach 2: Extracting Substring Before a Specific CharacterTo extract a substring that appears before a specific character or substring, you can use the strstr() function. PHP <?php $str = "Welcome to GeeksforGeeks"; $subStr = strstr($str, 'G'); echo $subStr; ?> OutputGeeksforGeeksApproach 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 <?php $str = "Welcome to GeeksforGeeks - A computer science portal"; if (preg_match('/to (.*?) -/', $str, $matches)) { echo $matches[1]; } ?> OutputGeeksforGeeksApproach 4: Using explode() FunctionThe explode() function in PHP is used to split a string into an array based on a specified delimiter. By splitting the string and then accessing the desired element of the resulting array, you can effectively extract a substring.Example: In this example, the string is split into an array of words using the space character as the delimiter. The third word (with zero-based index 2) is then accessed and printed. PHP <?php // Sample string $string = "Hello, this is an example string."; // Split the string into an array using a space as the delimiter $array = explode(" ", $string); // Accessing the desired element $substring = $array[2]; // Extracting "is" echo $substring; ?> OutputisUsing mb_substr() FunctionThe mb_substr() function is used to extract a substring from a string, similar to the substr() function but specifically designed for multibyte character encodings. This function takes three arguments: the input string, the starting position (zero-based index), and optionally the length of the substring to extract.Example PHP <?php // Sample string $string = "Hello, this is an example string."; // Function to extract a word by its position using mb_substr function getWordAtPosition($string, $wordPosition) { // Split the string into an array of words $words = explode(" ", $string); // Calculate the start position of the desired word $startPosition = 0; for ($i = 0; $i < $wordPosition; $i++) { $startPosition += mb_strlen($words[$i]) + 1; // +1 for the space delimiter } // Extract the desired word using mb_substr $wordLength = mb_strlen($words[$wordPosition]); $substring = mb_substr($string, $startPosition, $wordLength); return $substring; } // Extract the third word (zero-based index 2) $substring = getWordAtPosition($string, 2); // Extracting "is" echo $substring; ?> Outputis Comment More infoAdvertise with us Next Article How to Extract Substring from a String in PHP? B blalverma92 Follow Improve Article Tags : PHP PHP-string Similar Reads Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac 13 min read AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences 4 min read CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi 6 min read Like