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!
Help With Regular Expressions
Moderator: General Moderators
- snowrhythm
- Forum Commoner
- Posts: 75
- Joined: Thu May 04, 2006 1:14 pm
- Location: North Bay Area, CA
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Regex way:
Non regex way (faster, but less readable):
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 blockCode: 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
}- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
- snowrhythm
- Forum Commoner
- Posts: 75
- Joined: Thu May 04, 2006 1:14 pm
- Location: North Bay Area, CA