GGGGG
GGGGG

Reputation: 159

find the multiple occurrence of a word in a string using regular expression in php

I am trying to find the multiple occurrence of a string and also need to find the string after the word which is matched. I will explain you clearly.

First :

$string  = "Apple = A fruit which keeps u healthy\n Ball = Used to play games  \nApple = A fsadasdasdit wasdashich keeps u healthy\n";
$keyword = "apple";
$pattern = '/^.*?\b'.$keyword.'\b.*/i';
$res = preg_match_all($pattern , $string , $matches);
print_r($matches);

Here, I am trying to find the occurrence of apple in the string. But, it is showing only the first word apple. but it is not showing the second word.

Second : If I found all the words which matches the keyword. I need the string after the word. That means, Here, Apple matches two times

first time if the keyword matched, I will get this Apple = A fruit which keeps u healthy . Now, I need to store A fruit which keeps u healthy in one variable.

second time again the apple matched here, I will get Apple = A fsadasdasdit wasdashich keeps u healthy\n and I need to store A fsadasdasdit wasdashich keeps u healthy in another variable.

Please help me in doing this. Thanks in advance!

Upvotes: 2

Views: 4889

Answers (2)

Sabuj Hassan
Sabuj Hassan

Reputation: 39365

Try this one:

$pattern = '/.*?\b'.$keyword.'\b.*(?=[\n\r]|$)/i';

I have removed the ^ from the beginning of your regex. And added a lookahead (?=[\n\r]|$) at the end to see whether it is followed by a newline or end of string.

Upvotes: 2

anubhava
anubhava

Reputation: 785196

You need this regex:

'/\bapple\W*(.*)$/mi'

And your desired string is available in matched group #1.

Online Demo: http://regex101.com/r/nV2mI8

Code:

$re = '/\b' . $keyword . '\W*(.*)$/mi'; 
$str = 'Apple = A fruit which keeps u healthy
Ball = Used to play games
Apple = A fsadasdasdit wasdashich keeps u healthy'; 
 
preg_match_all($re, $str, $matches);

Upvotes: 3

Related Questions