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!

 

Link to comment
Share on other sites

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!"
?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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