Help With Regular Expressions

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
snowrhythm
Forum Commoner
Posts: 75
Joined: Thu May 04, 2006 1:14 pm
Location: North Bay Area, CA

Help With Regular Expressions

Post 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!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

:arrow: Moved to Regex
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
}
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

hehe... I thought it was just me who gave outright solutions on occasion.
User avatar
snowrhythm
Forum Commoner
Posts: 75
Joined: Thu May 04, 2006 1:14 pm
Location: North Bay Area, CA

Post 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.
Post Reply