1 回答

TA貢獻1836條經驗 獲得超13個贊
他的函數str_replace_first僅替換第一個匹配的字符串,并使用substr_count函數來了解字符串中還剩下多少特殊字符,我編寫了這個簡單的代碼:
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 關注
- 129 瀏覽
添加回答
舉報