PHP: Copy string from sub-string or character to sub-string or character

strcopy can make your string handling easier

Handy function returns part of string enclosed by sub-string or character

function strcopy($string, $fromsub, $tosub, $trimsub = true) {
  $pos = strpos($string, $fromsub);
  if ($pos === false)
   return $string;
  else {
   $string = substr($string, $pos+($trimsub ? strlen($fromsub) : 0));
   $pos = strpos($string, $tosub);
   if ($pos === false)
     return $string;
   else  
     return(substr($string, 0, $pos+($trimsub ? 0 : strlen($tosub))));
  }
}

Usage:

$myvar = 'Yahoo(Google)Bing'; 
echo strcopy($myvar,'(',')');   //result 'Google' 
echo strcopy($myvar,'(',')',false);   //result '(Google)'

Full Script:

<?php
function strcopy($string, $fromsub, $tosub, $trimsub = true) {
  $pos = strpos($string, $fromsub);
  if ($pos === false)
   return $string;
  else {
   $string = substr($string, $pos+($trimsub ? strlen($fromsub) : 0));
   $pos = strpos($string, $tosub);
   if ($pos === false)
     return $string;
   else  
     return(substr($string, 0, $pos+($trimsub ? 0 : strlen($tosub))));
  }
}

$myvar = 'Yahoo(Google)Bing'; 
echo strcopy($myvar,'(',')');  //result 'Google'
echo strcopy($myvar,'(',')',false); //result '(Google)'
?>