Horje
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:

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
)



Reffered: https://www.geeksforgeeks.org


PHP

Related
How to get the POST values from serializeArray in PHP ? How to get the POST values from serializeArray in PHP ?
PHP Program to Reverse Bit of a Number PHP Program to Reverse Bit of a Number
How to Use Foreach Loop with Multidimensional Arrays in PHP? How to Use Foreach Loop with Multidimensional Arrays in PHP?
How to Get All Values from an Associative Array in PHP? How to Get All Values from an Associative Array in PHP?
How to Populate Dropdown List with Array Values in PHP? How to Populate Dropdown List with Array Values in PHP?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14