2016-07-29 88 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

相关问题