Page 1 of 1

Help With Regular Expressions

Posted: Fri May 25, 2007 12:53 pm
by snowrhythm
I'm trying to find a way to extract a specific area of a string. say i have this in a file:

[begin file]

**start
here is some text
...more of the same text
still more of the same text.
**end

**startagain
here is some different text
...more of the same text
still more of the same text.
**end

[/file]

now what i want to do is read that file, and get what is in between the first "**start" and "**end", and then maybe i want to read the file a different time and extract the text between "**startagain" and "**end". basically i'm looking for a function that takes a string and two pointers, and gives you back what is in between the two pointers. does that make sense? if anyone knows a function for this or a good work-around, that would be great. I don't have much experience with reading files and slicing them up.

thanks in advance!

Posted: Fri May 25, 2007 1:09 pm
by Chris Corbyn
:arrow: Moved to Regex

Posted: Fri May 25, 2007 1:15 pm
by Chris Corbyn
Regex way:

Code: Select all

$start = "**start";
$end = "**end";
$regex = "/" . preg_quote($start) . "(.*?)" . preg_quote($end) . "/s";
preg_match($regex, $string, $matches);
var_dump($matches); //Look in $matches[1] for your text in the block
Non regex way (faster, but less readable):

Code: Select all

$start = "**start";
$end = "**end";

$start_pos = strpos($string, $start);
$end_pos = strpos($string, $end);

if ($start_pos < $end_pos)
{
  $match = substr($string, $start_pos+strlen($start), $end_pos);
}
else
{
  //No match
}

Posted: Fri May 25, 2007 2:38 pm
by Ollie Saunders
hehe... I thought it was just me who gave outright solutions on occasion.

Posted: Fri May 25, 2007 2:47 pm
by snowrhythm
that's awesome! and sorry about posting in the wrong forum....i didn't realize that a regex forum even existed. thanks for your help.