Mathew Kelly
Mathew Kelly

Reputation: 23

Get between every strings

Below is a function that can get a string with two other strings without a problem,

function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

Let's say I have code like this:

<code>Sample one</code>
<code>Sample two</code>
<code>Sample three</code>

When using GetBetween($content,'<code>',</code>') Instead of returning something like array("Sample one","Sample two","Sample three") it will only return the first one which is "Sample one" How can I get it to return EVERYTHING between the two things I specify? I would appreciate it if I could get a solution that isn't hardcoded with the "" tags because I will be needing this for many different things.

Upvotes: 2

Views: 216

Answers (3)

Jin
Jin

Reputation: 41

Guess you could try something like this,

function GetBetween($content,$tagname){
        $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
        preg_match($pattern, $string, $matches);
        unset($matches[0]);
        return $matches;
}

$content= "<code>Sample one</code><code>Sample two</code><code>Sample three</code>";

//The matching items are: 
print_r(GetBetween($content, 'code'));

Upvotes: 1

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Firstly regex is not the correct tool for parsing HTML/XML instead you can simply use DOMDocument like as

$xml = "<code>Sample one</code><code>Sample two</code><code>Sample three</code>";

$dom = new DOMDocument;
$dom->loadHTMl($xml);
$root = $dom->documentElement;
$code_data = $root->getElementsByTagName('code');
$code_arr = array();
foreach ($code_data as $key => $value) {
    $code_arr[] = $value->nodeValue;
}
print_r($code_arr);

Output:

Array
(
    [0] => Sample one
    [1] => Sample two
    [2] => Sample three
)

Upvotes: 4

Dave Chen
Dave Chen

Reputation: 10975

I've had to use a function like this, so I keep it handy:

//where a = content, b = start, c = end
function getBetween($a, $b, $c) {
    $y = explode($b, $a);
    $len = sizeof($y);
    $arr = [];
    for ($i = 1; $i < $len; $i++)
        $arr[] = explode($c, $y[$i])[0];
    return $arr;
}

Anything beyond this, you'll need to start using DomDocument.

Upvotes: 1

Related Questions