Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Part of the String if with conditional prefix [+ and suffix +]

Tags:

string

php

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...

like image 383
GusDeCooL Avatar asked Nov 14 '10 05:11

GusDeCooL


People also ask

How do I find the prefix and suffix of a string?

A prefix of a string S is a substring of S that occurs at the beginning of S. A suffix of a string S is a substring that occurs at the end of S.

How do you find the prefix of a string in C++?

The match_results::prefix() is an inbuilt function in C++ which is used to get the string which is preceding the matched string in the input target string.

How do I find the prefix of a string?

A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Input: words = ["a","b","c","ab","bc","abc"], s = "abc" Output: 3 Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc".


2 Answers

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

like image 66
codaddict Avatar answered Oct 15 '22 02:10

codaddict


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;
}
like image 2
Gumbo Avatar answered Oct 15 '22 01:10

Gumbo