php - getting a substring(charset independent) between given two offsets -


i want know if there built in php function can substring between given 2 keywords (keyword1 , keyword2). note keywords may repeat in string must able substring between xth keyword1 , yth keyword2. moreover, use unicode characters function should charset independen.

please me out handle problem.

e.g. $string=this cat hat in theater. $keyword1="is"; $keyword2="the";

task: how substring between 2nd occurance of "is" , 3nd occurance of "the" in given string above.

answer: " cat hat in "

you can use regular expressions:

$string = "this cat hat in theater";  $regex1 = "/.*? |^is/"; $regex2 = "/ .*| the$/"; echo preg_replace($regex1, '', preg_replace($regex2, ' the', $string)); 

edit here more generic code:

function find($text, $str, $offset) {     $len = strlen($text);     $search_len = strlen($str);     $count = 0;     ($i=0; $i<$len; ++$i) {         if (substr($text, $i, $search_len) == $str) {             if (++$count == $offset) {                 return $i;             }         }     }     return -1; }  function between($text, $word1, $offset1, $word2, $offset2) {     $start = find($text, $word1, $offset1);     $end = find($text, $word2, $offset2);     if ($start != -1 && $end != -1) {         return substr($text, $start + strlen($word1), $end-$start-strlen($word2));     } else {         return '';     } }   $string = "this cat hat in theater";  echo between($string, 'is', 2, 'the', 3); echo between($string, 'at', 1, 'at', 3); 

Comments