简体   繁体   中英

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!

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM