coryd.dev/server/utils/strings.php

73 lines
1.8 KiB
PHP

<?php
require __DIR__ . "/../../vendor/autoload.php";
use Kaoken\MarkdownIt\MarkdownIt;
use Kaoken\MarkdownIt\Plugins\MarkdownItFootnote;
function truncateText($text, $limit = 50, $ellipsis = "...")
{
if (mb_strwidth($text, "UTF-8") <= $limit) return $text;
$truncated = mb_substr($text, 0, $limit, "UTF-8");
$lastSpace = mb_strrpos($truncated, " ", 0, "UTF-8");
if ($lastSpace !== false) $truncated = mb_substr($truncated, 0, $lastSpace, "UTF-8");
return $truncated . $ellipsis;
}
function parseMarkdown($markdown)
{
if (empty($markdown)) return '';
$md = new MarkdownIt([
"html" => true,
"linkify" => true,
]);
$md->plugin(new MarkdownItFootnote());
return $md->render($markdown);
}
function parseCountryField($countryField) {
if (empty($countryField)) return null;
$delimiters = [',', '/', '&', ' and '];
$countries = [$countryField];
foreach ($delimiters as $delimiter) {
$tempCountries = [];
foreach ($countries as $country) {
$tempCountries = array_merge($tempCountries, explode($delimiter, $country));
}
$countries = $tempCountries;
}
$countries = array_map('trim', $countries);
$countries = array_map('getCountryName', $countries);
$countries = array_filter($countries);
return implode(', ', array_unique($countries));
}
function getCountryName($countryName) {
$isoCodes = new \Sokil\IsoCodes\IsoCodesFactory();
$countries = $isoCodes->getCountries();
$country = $countries->getByAlpha2($countryName);
if ($country) return $country->getName();
return ucfirst(strtolower($countryName));
}
function pluralize($count, $string, $trailing = '') {
if ((int)$count === 1) return $string;
return $string . 's' . ($trailing ? $trailing : '');
}
?>