1 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
他的函數(shù)str_replace_first僅替換第一個(gè)匹配的字符串,并使用substr_count函數(shù)來了解字符串中還剩下多少特殊字符,我編寫了這個(gè)簡(jiǎn)單的代碼:
function str_replace_first($from, $to, $content){
? ? $from = '/'.preg_quote($from, '/').'/';
? ? return preg_replace($from, $to, $content, 1);
}
$str = "dog *cat* ping goat *pizza* cow *rabbit";
$Open_OR_Closed_Tag = false;? // this for to know what tag should put
while (substr_count($str, '*') > 1 || $Open_OR_Closed_Tag) {
? ? if ($Open_OR_Closed_Tag) {
? ? ? ? $str = str_replace_first("*", "</strong>", $str);
? ? ? ? $Open_OR_Closed_Tag = false;
? ? } else {
? ? ? ? $str = str_replace_first("*", "<strong>", $str);
? ? ? ? $Open_OR_Closed_Tag = true;
? ? }
}
echo $str; // dog <strong>cat</strong> ping goat <strong>pizza</strong> cow rabbit*
- 1 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報(bào)