簡體   English   中英

在字符串php的所有部分上運行一個函數

[英]Run a function on all parts of string php

我構建了一個函數,它將在括號之間捕獲文本並將它們作為數組輸出。 但問題是我的函數只在字符串中第一次執行。

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]但不會每次都格式化其中的文本。

使用Regex將是這種事情的簡單解決方案

$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;

檢查我的解決方案 您的問題是,您在第一次調用后正在替換代碼,並且沒有循環:

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]';

echo preg_replace('#\[coupon\][\s]*(\w+)([\s&]+)(\w+)([\s&]+)(\w+)[\s]*\[\/coupon\]#i', '<b>$1</b> <i>$3</i><b>$5</b>', $Text);

使用ReGex解決方案(將捕獲所有文本和[優惠券] [/優惠券]並用新的String替換它們

preg_replace('#\[coupon\][A-Z0-9]+\[/coupon\]#i', $replaceText, $content);

如果你想保存你的[優惠券]標簽:

preg_replace('#(\[coupon\])[A-Z0-9]+(\[/coupon\])#i', '$1'.$replaceText.'$2', $content);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM