ldc-supportweb/app/Lib/Utils.php
2021-05-18 22:07:49 +02:00

34 lines
1.3 KiB
PHP

<?php
namespace App\Lib;
class Utils
{
public static function plainToHtml(string $text)
{
$text = e($text);
// url replace and email replace
$text = preg_replace_callback(
'/(?P<email>[^\s@]+@([^\s@.,]+\.)+[^\s@.,]{2,})|(?P<user>@\w*)|(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
function ($matches) {
$match = collect($matches)->first() ?? '';
if (filter_var($match, FILTER_VALIDATE_EMAIL)) {
return strlen($match) ? "<a href=\"mailto:$match\">$match</a>" : $match;
} elseif (isset($matches['user']) and strlen($matches['user'])) {
return sprintf(
'<span class="text-primary fw-bold font-weight-bold">%s</span>',
$matches['user']
);
} else {
$url = $match;
if (\strpos($url, 'http') === false and \strpos($url, 'https') === false) {
$url = sprintf('http://%s', $url);
}
return strlen($match) ? "<a href=\"$url\" target=\"_blank\">$match</a>" : $match;
}
},
$text
);
return nl2br($text);
}
}