I want to create custom tags for different things like bold, underline and italic without using a Markdown library/class.
For example
*Bold text*
/Italic text/
_Underlined text_
So the above would be changed to:
<strong>Bold text</strong>
<em>Italic text</em>
<u>Underlined text</u>
I have no idea where to begin and have been searching for a solution for ages.
I read a few tutorials on regular expressions but still unsure how to approach this.
Thanks in advanced.
Here is a recursive function to do that with regex. The tricky part (for me) was the use of forward slash /
which is also used in the close tags. So at first i insert {}
and replaces those with /
in the very end.
test text :
$input ="
*Bold text*
bla bla bla
/Italic text/
bla bla bla
_Underlined text_
bla bla bla
";
replace function :
function markdown(&$text, $code, $tag, $open) {
if (strpos($text, $code)) {
$insertTag=($open) ? '<'.$tag.'>' : '<{}'.$tag.'>';
$reg='['.preg_quote($code).']';
$text=preg_replace($reg, $insertTag, $text, 1);
markdown($text, $code, $tag, !$open);
} else {
return;
}
}
run :
markdown($input, '*', 'strong', true);
markdown($input, '/', 'em', true);
markdown($input, '_', 'u', true);
$input=str_replace('{}', '/', $input);
echo $input;
outputs :
<strong>Bold text</strong>
bla bla bla
<em>Italic text</em>
bla bla bla
<u>Underlined text</u>
bla bla bla