0

Quite simple problem (but difficult solution): I got a string in PHP like as follows:

['one']['two']['three']

And from this, i must extract the last tags, so i finally got three

it is also possible that there is a number, like

[1][2][3]

and then i must get 3

How can i solve this?

Thanks for your help!

Flo

2
  • Can the string contain more than tags? E.g. asdf['one']asdf['two']asdf['three']asdf? Commented Aug 3, 2011 at 11:20
  • No, there is the last tag at the end, and except these tags, there is no text. Commented Aug 3, 2011 at 11:35

3 Answers 3

2

Your tag is \[[^\]]+\].

3 Tags are: (\[[^\]]+\]){3}

3 Tags at end are: (\[[^\]]+\]){3}$

N Tags at end are: (\[[^\]]+\])*$ (N 0..n)

Example:

<?php
    $string = "['one']['two']['three'][1][2][3]['last']";
    preg_match("/((?:\[[^\]+]*\]){3})$/", $string, $match);
    print_r($match); // Array ( [0] => [2][3]['last'] [1] => [2][3]['last'] ) 
Sign up to request clarification or add additional context in comments.

2 Comments

I don't get it ... I tried with ereg, but it did not work :S I tried as follows: ereg("\[[^\]]+\]",$string), but it wont work. And another thing, all regex functions are marked as deprecated on php.net :S ...
Have an example as well as missing brackets added.
1

This tested code may work for you:

function getLastTag($text) {
    $re = '/
        # Match contents of last [Tag].
        \[              # Literal start of last tag.
        (?:             # Group tag contents alternatives.
          \'([^\']+)\'  # Either $1: single quoted,
        | (\d+)         # or $2: un-quoted digits.
        )               # End group of tag contents alts.
        \]              # Literal end of last tag.
        \s*             # Allow trailing whitespace.
        $               # Anchor to end of string.
        /x';
    if (preg_match($re, $text, $matches)) {
        if ($matches[1]) return $matches[1]; // Either single quoted,
        if ($matches[2]) return $matches[2]; // or non quoted digit.
    }
    return null; // No match. Return NULL.
}

Comments

1

Here is a regex that may work for you. Try this:

[^\[\]']*(?='?\]$)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.