Here’s a function which is useful when you need to extract some content between two delimiters. For instance you need to extract content using a robot that connects to a page.
<?php /* Credits: Bit Repository URL: http://www.bitrepository.com/extract-content-between-two-delimiters-with-php.html */ function extract_unit($string, $start, $end) { $pos = stripos($string, $start); $str = substr($string, $pos); $str_two = substr($str, strlen($start)); $second_pos = stripos($str_two, $end); $str_three = substr($str_two, 0, $second_pos); $unit = trim($str_three); // remove whitespaces return $unit; }
This is an usage example of this function:
$text = 'PHP is an acronym for "PHP: Hypertext Preprocessor".'; $unit = extract_unit($text, 'an', 'for'); // Outputs: acronym echo $unit; ?>
How it works?
First, we use stripos() to determine the numeric position of the first occurrence of needle in the haystack string. In our example, there are 7 characters from the beginning of the string until ‘an’.
$pos = stripos($string, $start);
Now, we will use this information to get the content of $string, from the $pos character until the last one:
an acronym for “PHP: Hypertext Preprocessor”.
$str = substr($string, $pos);
Remove ‘an’ from the recently created string:
acronym for “PHP: Hypertext Preprocessor”.
$str_two = substr($str, strlen($start));
Determine the number of characters from the beginning of $str_two until ‘for’ (9 in this case):
$second_pos = stripos($str_two, $end);
Now use this number to get the content from the beginning of the string until ‘for’:
$str_three = substr($str_two, 0, $second_pos);
The last variable would be equal with ‘ acronym ‘. Eventually, let’s strip the whitespaces from the beginning and ending of the string:
acronym
$unit = trim($str_three); // remove whitespaces
If you have any comments, suggestions regarding this snippet please post them.