在字符串php的所有部分上运行一个函数
发布时间:2020-05-31 00:51:31 所属栏目:PHP 来源:互联网
导读:我构建了一个函数,它将在括号之间捕获文本并将它们作为数组输出.但问题是我的函数只在字符串中第一次执行. function GetBetween($content,$start,$end){ $r = explode($start, $content); if (isset($r[1])){ $r = explode($end, $r[1]);
|
我构建了一个函数,它将在括号之间捕获文本并将它们作为数组输出.但问题是我的函数只在字符串中第一次执行. 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. 这意味着它每次都会替换[优惠券]和[/优惠券],但不会每次都格式化其中的文本. 检查我的解决方案您的问题是,您在第一次调用后正在替换代码,并且没有循环:function GetBetween($content,$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]');
$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,$string);
}
return $string;
}
$testString = "hello world [coupon]hello && bad && world[/coupon] and also to [coupon] the && bad && world [/coupon]";
$Text = srthhcdf($testString);
echo $Text; (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
