如果我有一个段落:
echo "^b(This sentence becomes bold), and ^i(this becomes italic).\nThen this becomes ^up(uppercase).";
如何将^ b,^ i,^ up,\ n替换为HTML标记?
此句子变为粗体,而此句子变为斜体。
然后这变成大写。
谢谢。
您可以尝试将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 result
echo $formattedText;
?>
如果您在辅助函数中编写此逻辑,那就更好了,这样以后您可以在其他地方更轻松地使用它。