Jump to content

How to find characters inbetween two tags


tc48

Recommended Posts

Hello,

I was wondering what would be the most simple way to find the text thats between to predefined tags in a string, and then set that text to a variable. Example...

 

I want the text inbetween these tags [set]iwantthistobeavariable[/set] to be set as a variable.

 

Thanks for your help!

 

I wrote this for that very purpose:

 

<?php

    function GetBetween($find1, $find2, $string) {
        $parse = explode($find1, $string, 2);
        $parse = substr($parse[1], 0, stripos($parse[1], $find2));
        return $parse;
    }

?> 

 

Usage:

 

<?php
    $string = GetBetween("[set]","[/set]", "[set]Hey![/set]");
    print $string; // prints "Hey!"
?>

im getting... Fatal error: Call to undefined function: stripos()

 

Ah, you have an old version of php. Just replace stripos() with strpos() and you should be OK, but it will be case-sensitive.

 

<?php

    function GetBetween($find1, $find2, $string, $case=false) {
        if ($case) {
            $find = strtoupper($find);
            $find2 = strtoupper($find2);
            $string = strtoupper($string);
        }
        $parse = explode($find1, $string, 2);
        $parse = substr($parse[1], 0, strpos($parse[1], $find2));
        return $parse;
    }

?> 

 

^ In this version you can toggle the case-sensitivity by setting $case to a value that evaluates to anything but false.

 

edit: Since you're parsing tags, this might be useful to you:

 

<?php
    //GetBetween function must be present

    function GetBetweenAll($find1, $find2, $string){
        $elements = array();
        while($word = GetBetween($find1, $find2, $string)){
            array_push($elements, $word);
            $string = str_replace($find1.$word.$find2, null, $string);
        }
        return $elements;
    }
?>

 

It preforms GetBetween on every instance of $find1STRING$find2 and returns the values in an array.

if (eregi ("<tag>(.*)</tag>", $line, $out)) {

        $tag = $out[1];

        break;

    }

 

now $tag is the first occurence of <tag></tag> , u may put this into array and get occurences, the same example is quoted in php manual

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.