Re: Re: Get the string in between two other strings
| From: | Tom Rogers | Date: | Thu, 17 Oct 2002 14:10:16 +0000 |
| Subject: | Re: Re: Get the string in between two other strings | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-120330@lists.php.net to get a copy of this message | ||
Hi,
Thursday, October 17, 2002, 10:33:43 PM, you wrote:
CC> I have looked at these, and they make no sense to me. I tried the substr
CC> function, but it all went a bit pear shaped.
Here is a way that will handle line breaks which tend to stuff up the
string functions:
<?
function find_string($string,$str1,$str2){
$x = $y = 0;
$state = 'S';
$r = '';
$p = '';
$len_str = strlen($string);
$len_x = strlen($str1);
$len_y = strlen($str2);
for($i=0;$i<$len_str;$i++){
switch($state){
case 'S': //try to find first string
if($string[$i] == $str1[$x]){
$state = 'P'; //possibly the start
$x++;
}
break;
case 'P':
if($string[$i] == $str1[$x]){
if($x == ($len_x -1)){
$state = 'R'; //found the first string
switch to result
}
else $x++; //keep looking
}
else{
$state = 'S'; // bummer .. back to search for
first string again
$x = 0;
}
break;
case 'R':
if($string[$i] == $str2[$y]){
$state = 'Q'; //quietly confident we have the
start of string 2
$y++;
$p .= $string[$i]; //save it in a temp var for now
}
else{
$r .= $string[$i]; // still in result mode
$y = 0;
}
break;
case 'Q':
if($string[$i] == $str2[$y]){
if($y == ($len_y -1)){ // yippee found the second string
return $r; //all done
}
else{
$p .= $string[$i]; //keep going
$y ++;
}
}
else{
$r .= $p; // add temp to result
$r .= $string[$i]; // don't forget this one
$p = '';
$y = 0;
$state = 'R'; // oops back to finding string 2
}
break;
}
}
return ''; //didn't find anything
}
$string = 'I need a function to get a string in between two other strings.';
$str1 = 'function to get';
$str2 = 'two other ';
echo "String: '$string' <br>";
echo "Str1: '$str1' <br>";
echo "Str2: '$str2' <br>";
echo "Extracted: '".find_string($string,$str1,$str2)."'<br>";
--
regards,
Tom