Simple: How to replace "all between" with php?

Viewed 51010
$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>

So what code am i looking for?

8 Answers

A generic and non-regex solution:

I've modified @felix-kling's answer. Now it only replaces text if it finds the needles.

Also, I've added parameters for replacing the needles, starting position and replacing all the matches.

I've used the mb_ functions for making the function multi-byte safe. If you need a case insensitive solution then replace mb_strpos calls with mb_stripos.

function replaceBetween($string, $needleStart, $needleEnd, $replacement,
                        $replaceNeedles = false, $startPos = 0, $replaceAll = false) {
    $posStart = mb_strpos($string, $needleStart, $startPos);

    if ($posStart === false) {
        return $string;
    }

    $start = $posStart + ($replaceNeedles ? 0 : mb_strlen($needleStart));
    $posEnd = mb_strpos($string, $needleEnd, $start);

    if ($posEnd === false) {
        return $string;
    }

    $length = $posEnd - $start + ($replaceNeedles ? mb_strlen($needleEnd) : 0);

    $result = substr_replace($string, $replacement, $start, $length);

    if ($replaceAll) {
        $nextStartPos = $start + mb_strlen($replacement) + mb_strlen($needleEnd);

        if ($nextStartPos >= mb_strlen($string)) {
            return $result;
        }

        return replaceBetween($result, $needleStart, $needleEnd, $replacement, $replaceNeedles, $nextStartPos, true);
    }

    return $result;
}
$string = "{ Some} how it {is} here{";

echo replaceBetween($string, '{', '}', '(hey)', true, 0, true); // (hey) how it (hey) here{

If you need to replace the portion too then this function is helpful:

$var = "Nate";

$body = "Hey there {firstName} have you already completed your purchase?";

$newBody = replaceVariable($body,"{","}",$var);

echo $newBody;

function replaceVariable($body,$needleStart,$needleEnd,$replacement){
  while(strpos($body,$needleStart){
      $start = strpos($body,$needleStart);
      $end = strpos($body,$needleEnd);
      $body = substr_replace($body,$replacement,$start,$end-$start+1);
  }
  return $body;
}

I had to replace a variable put into a textarea that was submitted. So I replaced firstName with Nate (including the curly braces).

Related