How to Extract Words from given String in PHP ?
Extracting words from a given string is a common task in PHP, often used in text processing and manipulation.
Below are the approaches to extract words from a given string in PHP:
Table of Content
- Using explode() function
- Using regular expressions
Using explode() function
In this approach, we are using the explode() function in PHP which is used to split a string into an array based on a specified delimiter. Here we use a space character as the delimiter to split the string into words.
Syntax:
words = explode(delimiter, string);
Example: This example uses explode() function to extract words from given string.
<?php
$string = "Welcome to w3wiki";
$words = explode(" ", $string);
print_r($words);
?>
Output
Array ( [0] => Welcome [1] => to [2] => w3wiki )
Using regular expressions
In this approach, we are using regular expressions to extract words from a string. We use the preg_match_all() function with a regex pattern to find all words in a string.
Syntax:
preg_match_all(pattern, string, matches);
Example: This example uses regular expressions to extract words from given string.
<?php
$string = "Hello Beginner";
preg_match_all('/\b\w+\b/', $string, $matches);
$words = $matches[0];
print_r($words);
?>
Output
Array ( [0] => Hello [1] => Beginner )
Contact Us