[英]find the multiple occurrence of a word in a string using regular expression in php
我正在嘗試查找字符串的多次出現,還需要在匹配的單詞后找到字符串。 我會清楚地向你解釋。
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);
在這里,我試圖在字符串中查找蘋果的出現。 但是,它只顯示第一個字蘋果。 但它沒有顯示第二個單詞。
Second :
如果我找到所有與關鍵字匹配的單詞。 我需要字后面的字符串。 這意味着,蘋果在這里比賽了兩次
第一次,如果關鍵字匹配,我將得到這個Apple = A fruit which keeps u healthy
。 現在,我需要存儲A fruit which keeps u healthy
。
第二次蘋果在這里匹配,我將得到Apple = A fsadasdasdit wasdashich keeps u healthy\\n
,我需要在另一個變量中存儲A fsadasdasdit wasdashich keeps u healthy
。
請幫助我做到這一點。 提前致謝!
您需要此正則表達式:
'/\bapple\W*(.*)$/mi'
並且您想要的字符串在匹配的組#1中可用。
碼:
$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);
試試這個:
$pattern = '/.*?\b'.$keyword.'\b.*(?=[\n\r]|$)/i';
我從您的正則表達式開頭刪除了^
。 並在末尾添加了前瞻(?=[\\n\\r]|$)
,以查看其后是換行符還是字符串末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.