Replacing text between two delimiters

I'm trying to get text between two characters that need to be replaced with preg_replace, but, alas, it’s still not entirely correct, since I get empty output, which is an empty string, this is what I still have

$start = '["';
$end   = '"]';
$msg   = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);

So, the result of the output I'm looking for will be as follows:

normal text [everythingheregone] after text 

For

 normal text [test] after text
+5
source share
5 answers

You define $ start and $ end as arrays, but use it as regular variables. Try changing the code:

$start = '\[';
$end  = '\]';
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);
+8
source

What about

$str  = "normal text [everythingheregone] after text";
$repl = "test";
$patt = "/\[([^\]]+)\]/"; 
$res  = preg_replace($patt, "[". $repl ."]", $str);

Should go out normal text [test] after text

EDIT

Demo screenshot here

+1
source

,

function getBetweenStr($string, $start, $end)
    {
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);    
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
    }

function getAllBetweenStr($string, $start, $end)
    {
        preg_match_all( '/' . preg_quote( $start, '/') . '(.*?)' . preg_quote( $end, '/') . '/', $string, $matches);
        return $matches[1];
    }
+1
$row['body']= "normal text [everythingheregone] after text ";
$start = '\[';
$end = '\]';
$msg = preg_replace('#'.$start.'.*?'.$end.'#s', '$1 [test] $3', $row['body']);
//output: normal text [test] after text done
0

. : \[.*?]

<?php
$string = 'normal text [everythingheregone] after text ';
$pattern = '\[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
?>
0

All Articles