Songo
Songo

Reputation: 5736

Search for a string in a php file with a start and end

I'm having problems writing a php function to search for a certain text in a php file. I'm not good with regular expressions so I think that's the problem.

I need the regular expression to have a start word and end word and should return the text found in between. This is what I tried:

$handle1 = fopen($file, "r");
$fileContents = fread($handle1,filesize($file));
if (preg_match('/'.$start. '((.|\n)*)'. $end.'/', $fileContents, $match)) {
$text=preg_split('/'.$start.'((.|\n)*)'. $end.'/', $match[0]);
echo $text. " found in $file<br/>";
}

Can anybody help please ?

Upvotes: 4

Views: 11527

Answers (3)

Abdul Jabbar
Abdul Jabbar

Reputation: 5931

I love these two solutions

function GetBetween($content,$start,$end)
{
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}


function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);   
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

I also made few benchmarks as well with both solutions above and both are giving almost the same time. You can test it as well. I gave both functions a file to read which had about 60000 characters (reviewed with Ms. Word's word count) and both functions resulted in about 0.000999 seconds to find.

$startTime = microtime(true);
GetBetween($str, '<start>', '<end>');
echo "Explodin Function took: ".(microtime(true) - $startTime) . " to finish<br />";

$startTime = microtime(true);
get_string_between($str, '<start>', '<end>');
echo "Subsring Function took: ".(microtime(true) - $startTime) . " to finish<br />";

Upvotes: 3

Yoshi
Yoshi

Reputation: 54649

<?php
$str = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. ...';

$start = 'sadipscing';
$end = 'dolore';

$pattern = sprintf(
    '/%s(.+?)%s/ims',
    preg_quote($start, '/'), preg_quote($end, '/')
);

if (preg_match($pattern, $str, $matches)) {
    list(, $match) = $matches;
    echo $match;
}

Where $str should be the contents of your file.

Have a look at: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php for the i, m and s modifiers.

Upvotes: 9

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25435

You don't need regex for this.

function getText($string, $start, $end)
{
   $text = "";
   $posStart = strrpos($string, $start);
   $posEnd = strrpos($string, $end, $posStart);
   if($posStart > 0 && $posEnd > 0)
   {
       $text = substr($string, $posStart, strlen($string) - $posEnd));
   }
   return $text;
}

Hope this helps.

Upvotes: 6

Related Questions