2013-01-02 48 views
3

我有一个包含项目列表的PHP字符串,我想获得最后一项。PHP preg_match获取最后一项

现实情况要复杂得多,但它归结为:

$Line = 'First|Second|Third'; 
if (preg_match('@^.*|(?P<last>.+)[email protected]', $Line, $Matches) > 0) 
{ 
    print_r($Matches); 
} 

我希望Matches['last']遏制“三”,但它不工作。相反,我得到匹配[0]包含完整的字符串,没有别的。 我在做什么错?

请没有解决方法,我可以做我自己,但我真的很喜欢这个用的preg_match工作

+3

请问您能解释为什么它必须是正则表达式吗?如果分隔符是只是管道,然后'结束(爆炸(“|”,$线)'真的会容易得多或许与strrpos SUBSTR – Gordon

+0

如果你只是想最后一个部分,你可以做'SUBSTR(strrchr(。 $线,“|”),1);'不知道后面需要使用正则表达式的推理,你可能解释为何 –

+0

它必须是正则表达式,因为实际的字符串比我的例子更复杂一点?你是对的,我绝不会在这样一个简单的字符串上使用正则表达式。 –

回答

2

如果你的语法总是有点相同,我的意思是,使用日Ë|作为分隔符,你可以做到以下几点,如果你喜欢它。

$Line = 'First|Second|Third' ; 
$line_array = explode('|', $Line); 
$line_count = count($line_array) - 1; 

echo $line_array[$line_count]; 

$Line = 'First|Second|Third' ; 
$line_array = explode('|', $Line); 
end($line_array); 

echo $line_array[key($line_array)]; 
2

只需使用:

$Line = 'First|Second|Third' ; 
    $lastword = explode('|', $line); 
    echo $lastword['2']; 
0

PHP的preg_match的实例,以获得最后一场比赛:

<?php 
    $mystring = "stuff://sometext/2010-01-01/foobar/2016-12-12.csv"; 
    preg_match_all('/\d{4}\-\d{2}\-\d{2}/', $mystring, $matches); 
    print_r($matches); 
    print("\nlast match: \n"); 
    print_r($matches[0][count($matches[0])-1]); 
    print("\n"); 
?> 

打印返回的整个对象和最后一个匹配项:

Array 
(
    [0] => Array 
     (
      [0] => 2010-01-01 
      [1] => 2016-12-12 
     ) 

) 

last match: 
2016-12-12