Since I sanitize all the user-provided string before upload them to the DB, I wanted to give the users the possibility to format text as it happens here on Stack Exchange or on WhatsApp:
*word*
-> bold_word_
-> italic
This class contains two functions:
upload()
: is called when the user upload a text and it replaces*word*
with<b>word</b>
,_word_
with<i>word</i>
and\n
with<br />
download()
: is called when the user wants to modify the text and it does exactly the opposite; it replaces HTML tags with the custom signs*
and_
My questions:
- Could be this code considered as a real class in the way of thinking or is it just procedural code put into a class?
- Would you improve it in any way?
- Do you have any suggestion to write it better?
class txtFormatting {
private $text;
function __construct($text)
{
$this->text = $text;
}
function upload() {
$this->text = preg_replace('/[ \t]+/', ' ', $this->text); //transforms: 2/+ whitespaces -> 1 whitespace
$this->text = nl2br($this->text); //transforms: \n -> <br />
$this->text = preg_replace(array("/\r\n/", "/\n\r/", "/\n/", "/\r/"), '', $this->text);
$this->text = explode(' ', $this->text); //each word becomes a value
$regexAY =
[
'/[*]{1}[a-zA-Z0-9]+[*]{1}/' =>
[
"pattern" => "*",
"openTag" => "<b>",
"closeTag" => "</b>"
],
'/[_]{1}[a-zA-Z0-9]+[_]{1}/' =>
[
"pattern" => "_",
"openTag" => "<i>",
"closeTag" => "</i>"
]
];
$newText = [];
foreach ($this->text as $key => $word) {
foreach ($regexAY as $regex => $value) {
if (preg_match($regex, $word)) {
$pattern = $regexAY[$regex]["pattern"];
$openTag = $regexAY[$regex]["openTag"];
$closeTag = $regexAY[$regex]["closeTag"];
$word = preg_replace('/\\' .$pattern. '(.*?)\\' .$pattern. '/', $openTag. '$1' .$closeTag, $word); // /\*(.*?)\*/ OR /_(.*?)_/
}
}
if ($word !== '') { array_push($newText, $word); }
}
return $this->text = implode(' ', $newText);
}
function download() {
/*function br2nl() {
return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $this->text); // /\<br(\s*)?\/?\>/i
}*/
$this->text = preg_replace('/\<br(\s*)?\/?\>/i', "\n", $this->text);
$this->text = explode(' ', $this->text);
$regexAY =
[
'/<b>[a-zA-Z0-9]+<\/b>/' =>
[
"pattern" => ["/<b>/", "/<\/b>/"],
"replacement" => "*"
],
'/<i>[a-zA-Z0-9]+<\/i>/' =>
[
"pattern" => ["/<i>/", "/<\/i>/"],
"replacement" => "_"
]
];
$newText = [];
foreach ($this->text as $key => $word) {
foreach ($regexAY as $regex => $value) {
if (preg_match($regex, $word)) {
$word = preg_replace($regexAY[$regex]["pattern"], $regexAY[$regex]["replacement"], $word);
}
}
if ($word !== '') { array_push($newText, $word); }
}
return $this->text = implode(' ', $newText);
}
}
$text = " This _is_ _just_ _a test_
*text*
so _don't_
consider it just *read*
it";
$a = new txtFormatting($text);
echo $a->upload()."\n";
$text = "This <i>is</i> <i>just</i> _a test_<br /> <b>text</b><br /> so <i>don't</i><br /> consider it just <b>read</b><br /> it";
$b = new txtFormatting($text);
echo $b->download()."\n";