Open In App

How to Extract Words from given String in PHP ?

Last Updated : 25 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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
<?php
    $string = "Welcome to GeeksForGeeks";
    $words = explode(" ", $string);
    print_r($words);

?>

Output
Array
(
    [0] => Welcome
    [1] => to
    [2] => GeeksForGeeks
)

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
<?php
    $string = "Hello Geeks";
    preg_match_all('/\b\w+\b/', $string, $matches);
    $words = $matches[0];
    print_r($words);
?>

Output
Array
(
    [0] => Hello
    [1] => Geeks
)

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads