PHP: Getting part of string after and before given sub-string or character


Easiest way of getting part of string given to its sub-string or character
function that returns part of string after specified sub-string

function strafter($string, $substring) {
  $pos = strpos($string, $substring);
  if ($pos === false)
   return $string;
  else  
   return(substr($string, $pos+strlen($substring)));
}
function that returns part of string before specified sub-string
function strbefore($string, $substring) {
  $pos = strpos($string, $substring);
  if ($pos === false)
   return $string;
  else  
   return(substr($string, 0, $pos));
}
Usage:
$myvar = 'Anti,Christ,World'; 

$myvar = strafter($myvar,',');  //$myvar = 'Christ,World' 

echo $myvar; //result 'Christ,World'
echo strbefore($myvar,','); //result 'Christ' 
Full Script:
<?php
function strafter($string, $substring) {
  $pos = strpos($string, $substring);
  if ($pos === false)
   return $string;
  else  
   return(substr($string, $pos+strlen($substring)));
}

function strbefore($string, $substring) {
  $pos = strpos($string, $substring);
  if ($pos === false)
   return $string;
  else  
   return(substr($string, 0, $pos));
} 

 
$myvar = 'Anti,Christ,World'; 

$myvar = strafter($myvar,',');  //$myvar = 'Christ,World' 

echo $myvar; //result 'Christ,World'
echo strbefore($myvar,','); //result 'Christ' 
?> 
PHP: Getting part of string after and before given sub-string or character PHP: Getting part of string after and before given sub-string or character Reviewed by Unknown on December 20, 2017 Rating: 5

No comments:

Powered by Blogger.