echo "^b(This sentence becomes bold), and ^i(this becomes italic).\nThen this becomes ^up(uppercase).";
如何将 ^b, ^i, ^up, \n 替换成 HTML 标签?
这句话变为粗体,而this 变为斜体。
然后这变成大写。
谢谢。
慕容森
浏览 160回答 1
1回答
红糖糍粑
您可以尝试将 preg_replace() 与模式一起使用来执行此操作:<?php// your example text$text = "^b(This sentence becomes bold), and ^i(this becomes italic).\nThen this becomes ^up(uppercase).";// array of patterns$patterns = [];$patterns[0] = "/\^b\((.*?)\)/";$patterns[1] = "/\^i\((.*?)\)/";$patterns[2] = "/\^up\((.*?)\)/";// array of replacements $replacements = [];$replacements[0] = '<b>${1}</b>';$replacements[1] = '<i>${1}</i>';$replacements[2] = '<span style="text-transform:uppercase;">${1}</span>'; // or use something better here// process the text$formattedText = preg_replace($patterns, $replacements, $text); // see the resultecho $formattedText;?>如果你把这个逻辑写在一个辅助函数中会好得多,这样你以后可以在不同的地方更容易地使用它。