Search code examples
phppreg-match

PHP preg_match get the last item


I have a PHP string with a list of items, and I would like to get the last one.

The reality is much more complex, but it boils down to:

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

I expect Matches['last'] to contain 'Third', but it does not work. Rather, I get Matches[0] to contain the full string and nothing else. What am I doing wrong?

Please no workarounds, I can do it myself but I would really like to have this working with preg_match


Solution

  • You have this:

    '@^.*|(?P<last>.+)$@'
         ^
    

    ... but I guess you are looking for a literal |:

    '@^.*\|(?P<last>.+)$@'
         ^^