我正在尝试使用正则表达式来获取子字符串的每一次出现,但它不能正常工作
$txt='[[Created::11 January 2014]][[Assignee::David]][[Assignee::root]][[Title::Test]]';
$re1='.*?'; # Non-greedy match on filler
$re2='(\\[\\[Assignee::.*?\\]\\])'; # Square Braces 1
preg_match_all ("/".$re2."/", $txt, $matches);
$sbraces1=$matches[1][0];
$sbraces2=$matches[2][0];
print "($sbraces1) ($sbraces2) \n";
输出:([[Assignee :: David]])()
字符串可以包含任意数量的Assignees,我需要过滤每一个。包含Assignees名称的数组将是完美的,但正如您所见,preg_match_all(...)只找到第一个匹配,我不知道为什么。 我的代码出了什么问题?
谢谢!
最诚挚的问候 大卫
答案 0 :(得分:0)
你有两个问题: 你实际上并没有展示所有匹配的受让人。相反,您只显示第一个(由于您的$ matches [1] [0]和$ matches [2] [0]字段(显示两个子模式的FIRST匹配)。 2.您可能只想显示受让人的姓名而不是整个文本。
试试这样:
<?php
$txt='[[Created::11 January 2014]][[Assignee::David]][[Assignee::root]][[Title::Test]]';
preg_match_all ('#\\[\\[Assignee::(.+)\\]\\]#U', $txt, $matches); // The U modifier makes this UNgreedy
$matched_assignees = implode(', ', $matches[1]); // we now glue together all the assignees matched with a ", " between them to form a nice long string.
echo 'Matched assignees: ', $matched_assignees; // output them