arrays - Run a function on all parts of string php -
i built function capture text between brackets , output them array. problem function executes first time in 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 matches first [coupon] , [/coupon] not others. when string
hello world [coupon]hello && bad && world[/coupon] , [coupon] && bad && world [/coupon]
it outputs
hello world <b>hello </b> <i> bad </i><b> world</b> , && bad && world.
which means replaces [coupon]
, [/coupon]
every time doesn't formats text inside them every time.
check solution. problem is, replacing codes after first call, , there no loop:
function getbetween($content, $start, $end) { $pieces = explode($start, $content); $inners = array(); foreach ($pieces $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 $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] , [coupon] && bad && world [/coupon]"; $text = srthhcdf($teststring); echo $text;
Comments
Post a Comment