Darcy Clarkebuilding products / experiences / communities & culture

Toggle Main Navigation

Apr 26, 2011

Strip out text between two tags in a string - PHP

Posted in "development"


If you're not a REGEX (Regular Expression) mastermind it can be hard to use something like PHP's preg_match() function which is very useful for obtaining the code contained within the selector given. That said, years ago, before I knew any Regular Expressions I wrote a handy strip function that will find the content contained between to sets of strings passed. It's pretty handy and you can use a offset as the last parameter if you'd like otherwise it defaults to zero.

function strip($startTag,$endTag,$text,$pos=0){
  if(!is_integer($pos)){
    $pos = false;
    return false;
  }
  $pos1 = strpos($text,$startTag,$pos);
  if(!is_integer($pos1)){
    $pos = false;
    return false;
  }
  $pos1 += strlen($startTag);
  $pos2 = strpos($text,$endTag,$pos1);
  if(!is_integer($pos2)){
    $pos = false;return false;
  }
  $res = substr($text,$pos1,$pos2-$pos1);
  $pos = $pos2 + strlen($endTag);
  return $res;
}