我构建了一个函数,它将捕获括号之间的文本并将它们输出为数组。但问题是我的函数只在字符串中第一次执行。
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);
但它只匹配第一个 [coupon] 和 [/coupon] 而不是其他的。 就像当字符串是
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;
关于php - 对字符串 php 的所有部分运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27502522/