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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With