tc48 Posted July 12, 2007 Share Posted July 12, 2007 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! Quote Link to comment Share on other sites More sharing options...
infid3l Posted July 12, 2007 Share Posted July 12, 2007 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!" ?> Quote Link to comment Share on other sites More sharing options...
teng84 Posted July 12, 2007 Share Posted July 12, 2007 use the regex Quote Link to comment Share on other sites More sharing options...
tc48 Posted July 12, 2007 Author Share Posted July 12, 2007 im getting... Fatal error: Call to undefined function: stripos() Quote Link to comment Share on other sites More sharing options...
infid3l Posted July 12, 2007 Share Posted July 12, 2007 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. Quote Link to comment Share on other sites More sharing options...
logged_with_bugmenot Posted July 12, 2007 Share Posted July 12, 2007 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.