5

How can I get part of the string with conditional prefix [+ and suffix +], and then return all of it in an array?

example:

$string = 'Lorem [+text+] Color Amet, [+me+] The magic who [+do+] this template';

// function to get require
function getStack ($string, $prefix='[+', $suffix='+]') {
    // how to get get result like this?
    $result = array('text', 'me', 'do'); // get all the string inside [+ +]

    return $result;
}

many thanks...

codaddict
  • 445,704
  • 82
  • 492
  • 529
GusDeCooL
  • 5,639
  • 17
  • 68
  • 102
  • 1
    This should be a fairly simple regex. Something like `preg_match_all("/\\[\\+(.*?)\\+\\]/");` and then get group 1 of the results. – Alxandr Nov 14 '10 at 05:20

2 Answers2

5

You can use preg_match_all as:

function getStack ($string, $prefix='[+', $suffix='+]') {
        $prefix = preg_quote($prefix);
        $suffix = preg_quote($suffix);
        if(preg_match_all("!$prefix(.*?)$suffix!",$string,$matches)) {
                return $matches[1];
        }
        return array();
}

Code In Action

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 1
    You might want to add the delimiter `/` to the `preg_quote()` calls. – BoltClock Nov 14 '10 at 16:13
  • 1
    @codaddict: I think you misunderstood BoltClock. `preg_quote` does not escape the delimiter unless it’s one of PCRE’s special characters. So if you’re using `/` or `!` as delimiter, you need to pass it to `preg_quote` to have it escaped. – Gumbo Nov 14 '10 at 16:43
  • @Gumbo: The manual: http://php.net/manual/en/function.preg-quote.php says: The special regular expression characters are: `. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -` which includes `!`. So it should work fine. – codaddict Nov 14 '10 at 17:37
2

Here’s a solution with strtok:

function getStack ($string, $prefix='[+', $suffix='+]') {
    $matches = array();
    strtok($string, $prefix);
    while (($token = strtok($suffix)) !== false) {
        $matches[] = $token;
        strtok($prefix);
    }
    return $matches;
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844