Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function on all parts of string php

Tags:

arrays

php

I built a function which will capture text between brackets and output them as array. But the problem is that my function only executes first time in the string.

function GetBetween($content,$start,$end){ 
    $r = explode($start, $content); 

    if (isset($r[1])){ 
        $r = explode($end, $r[1]); 
        return $r[0]; 
    } 
    return ''; 
}

function srthhcdf($string){
    $innerCode = GetBetween($string, '[coupon]', '[/coupon]');
    $iat = explode('&&', $innerCode);
    $string = str_replace('[coupon]','',$string);
    $string = str_replace('[/coupon]','',$string);
    $newtext = '<b>'.$iat[0].'</b> <i>'.$iat[1].'</i><b>'.$iat[2].'</b>';
    $string = str_replace($innerCode,$newtext,$string);
    return $string;
}
$Text = srthhcdf($Text);

But it matches only first [coupon] and [/coupon] not others. Like when the string is

hello world [coupon]hello && bad && world[/coupon] and also to [coupon] the && bad && world [/coupon]

It outputs

Hello world <b>hello </b> <i> bad </i><b> world</b> and also to the && bad && world.

Which means it replaces [coupon] and [/coupon] every time but doesn't formats the text inside them every time.

like image 294
IdidntKnewIt Avatar asked Oct 19 '22 20:10

IdidntKnewIt


1 Answers

Check my solution. Your problem is, you are replacing the codes after the first call, and there is no loop:

function GetBetween($content, $start, $end) {
    $pieces = explode($start, $content);
    $inners = array();
    foreach ($pieces as $piece) {
        if (strpos($piece, $end) !== false) {
            $r = explode($end, $piece);
            $inners[] = $r[0];
        }
    }
    return $inners;
}

function srthhcdf($string) {
    $innerCodes = GetBetween($string, '[coupon]', '[/coupon]');
    $string = str_replace(array('[coupon]', '[/coupon]'), '', $string);
    foreach ($innerCodes as $innerCode) {
        $iat = explode('&&', $innerCode);
        $newtext = '<b>' . $iat[0] . '</b> <i>' . $iat[1] . '</i><b>' . $iat[2] . '</b>';
        $string = str_replace($innerCode, $newtext, $string);
    }
    return $string;
}

$testString = "hello world [coupon]hello && bad && world[/coupon] and also to [coupon] the && bad && world [/coupon]";
$Text = srthhcdf($testString);
echo $Text;
like image 80
vaso123 Avatar answered Oct 22 '22 12:10

vaso123