亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用html標簽替換特殊字符

如何用html標簽替換特殊字符

PHP
慕標琳琳 2023-09-22 17:09:57
我遇到了挑戰,我想找到 2 個特殊字符之間的所有字符串,并用一些 html 標簽替換特殊字符。例如,$str = "dog *cat* ping goat *pizza* cow rabbit*";我想要一個函數從字符串中獲取 - cat 和 Pizza 然后返回$str = "dog <strong>cat</strong> ping goat <strong>pizza</strong> cow rabbit*";請注意,它cow rabbit被忽略,因為字符串中沒有開頭 *。我本質上想做的是根據這個 WhatsApp 文檔 - https://faq.whatsapp.com/general/chats/how-to-format-your-messages/找到字符串之間的特殊格式字符并替換為 HTML相等的。我該如何實現這一目標?
查看完整描述

1 回答

?
開心每一天1111

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*


查看完整回答
反對 回復 2023-09-22
  • 1 回答
  • 0 關注
  • 129 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號