2016-07-29 85 views
3

我想查找字符串中「%」中的所有子字符串,但我不明白爲什麼它只能找到「id」。正則表達式找到%PHP內的所有子字符串

$test = '<img src="%get_love%" alt="%f_id%" title="%id%" />'; 
$token_regex_inside_tags = "/<([^>]*%([\w]+)%[^>]*)>/"; 
preg_match_all($token_regex_inside_tags, $test, $matches); 

回答

4

假設: - 我假設你需要內%查找內容只有<>之間的英寸

你可以使用這個表達式,它使用\G

(?:\G(?!\A)|<)[^%>]*%([^%>]*)% 

Regex Demo

正則表達式擊穿

(?: 
    \G(?!\A) #End of previous match 
    | #Alternation 
    < #Match < literally 
) 
[^%>]* #Find anything that's not % or > 
%([^%>]*)% #Find the content within % 

在您的正則表達式

< #Matches < literally 
(
    [^>]* #Moves till > is found. Here its in end 
    %([\w]+)% #This part backtracks from last but is just able to find only the last content within two % 
    [^>]* 
)> 
+1

感謝您的詳細解釋! – coffeeak

相關問題