我构建了一个函数,它将捕获括号之间的文本并将它们输出为数组。但问题是我的函数只在字符串中第一次执行。
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);
但它只匹配第一个 [优惠券] 和 [/优惠券] 而不匹配其他。就像当字符串是
hello world [coupon]hello && bad && world[/coupon] and also to [coupon] the && bad && world [/coupon]
它输出
Hello world <b>hello </b> <i> bad </i><b> world</b> and also to the && bad && world.
这意味着它每次都会替换[coupon]
和[/coupon]
,但不会每次都格式化其中的文本。
检查我的解决方案。您的问题是,您在第一次调用后替换代码,并且没有循环:
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;
使用正则表达式将是此类事情的简单解决方案
$Text = "hello world [coupon]hello && bad && world[/coupon] and also to [coupon] the && bad && world [/coupon]";
$result = preg_replace('%'[coupon]([^[]*)'[/coupon]%', '<i>'1</i>', $Text);
print $result;
请尝试以下代码:
$Text = 'hello world [coupon]hello && bad && world[/coupon] and also to [coupon] the && bad && world [/coupon]';
echo preg_replace('#'[coupon']['s]*('w+)(['s&]+)('w+)(['s&]+)('w+)['s]*'['/coupon']#i', '<b>$1</b> <i>$3</i><b>$5</b>', $Text);
使用 ReGex 的解决方案(将捕获所有文本和 [coupon][/coupon] 并将它们替换为新的字符串
preg_replace('#'[coupon'][A-Z0-9]+'[/coupon']#i', $replaceText, $content);
如果您想保存您的 [优惠券] 标签 :
preg_replace('#('[coupon'])[A-Z0-9]+('[/coupon'])#i', '$1'.$replaceText.'$2', $content);