php - 对字符串 php 的所有部分运行一个函数

标签 php arrays

我构建了一个函数,它将捕获括号之间的文本并将它们输出为数组。但问题是我的函数只在字符串中第一次执行。

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/

相关文章:

php - zend_form : should I use one right in the layout

php - 获取php中的JS值

javascript - Array.prototype.includes 在 Node js 版本 <= 4

php自定义日程日历无法在日期单元格中显示客户姓名

php - 图书网站条码扫描仪

javascript - 如何在不重写整个应用程序的情况下对结果进行分块(延迟加载?)(Laravel + jQuery,SPA 风格)

c# - 对如何使用 List<string>[] 感到困惑

arrays - 提高阵列访问速度

javascript - JavaScript 中仅获取满足特定属性的对象

javascript - Reactjs: TypeError: 无法读取未定义的属性 'eventSlots'