简体   繁体   English

使用php中的正则表达式查找字符串中单词的多次出现

[英]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. Second :如果我找到所有与关键字匹配的单词。 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 . 第一次,如果关键字匹配,我将得到这个Apple = A fruit which keeps u healthy Now, I need to store A fruit which keeps u healthy in one variable. 现在,我需要存储A fruit which keeps u healthy

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. 第二次苹果在这里匹配,我将得到Apple = A fsadasdasdit wasdashich keeps u healthy\\n ,我需要在另一个变量中存储A fsadasdasdit wasdashich keeps u healthy

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. 并且您想要的字符串在匹配的组#1中可用。

Online Demo: http://regex101.com/r/nV2mI8 在线演示: 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. 并在末尾添加了前瞻(?=[\\n\\r]|$) ,以查看其后是换行符还是字符串末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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