I am trying to make a whatsapp style text post. When user create text like this:
*Hi* ~how are you~ _where are you?_
then this text is automatically changing like this
Hi how are you where are you
I know i can do it with php regex like this:
The example is for bold text:
function makeBoldText($orimessage){ $message = $orimessage; $regex = "/*([w]*)*/"; $message = preg_replace($regex, '<strong>$0</strong>', $message); return $message ; } echo makeBoldText($message);
But there is a problem it should be remove *
when text is outputed.
The other regex also should be like this:
Bold:
/*([w]*)*/
Italic:
/_([w]*)_/
strikethrough:
/~([w]*)~/
My question is, can I do all this in one regex? And can the special characters be deleted when the output is made?
Advertisement
Answer
You may use a single call to preg_replace_callback
here:
$styles = array ( '*' => 'strong', '_' => 'i', '~' => 'strike'); function makeBoldText($orimessage) { global $styles; return preg_replace_callback('/(?<!w)([*~_])(.+?)1(?!w)/', function($m) use($styles) { return '<'. $styles[$m[1]]. '>'. $m[2]. '</'. $styles[$m[1]]. '>'; }, $orimessage); } // call it as: $s = '*Hi* ~how are you~ _where are you?_'; echo makeBoldText($s); //=> <strong>Hi</strong> <strike>how are you</strike> <i>where are you?</i>