Skip to content

Instantly share code, notes, and snippets.

@jprivet-dev
Last active January 12, 2023 21:32
Show Gist options
  • Save jprivet-dev/1e55f90d2bb29891b831a48d286171ae to your computer and use it in GitHub Desktop.
Save jprivet-dev/1e55f90d2bb29891b831a48d286171ae to your computer and use it in GitHub Desktop.
PHP - Tips
<?php
declare(strict_types=1);
namespace App\Util;
abstract class StringUtil
{
/**
* Replace the accents in a string.
*
* @param string $string
* @return string
*/
public static function noAccent(string $string): string
{
$lettersAccent = "ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,u";
$lettersNoAccent = "c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,u";
$search = explode(",", sprintf("%s,%s", $lettersAccent, mb_strtoupper($lettersAccent)));
$replace = explode(",", sprintf("%s,%s", $lettersNoAccent, mb_strtoupper($lettersNoAccent)));
return str_replace($search, $replace, $string);
}
/**
* Convert a string into camelCase format.
*
* @param string $string
* @return string
*
* @see https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php#L117
*/
public static function camelCase(string $string): string
{
$string = self::noAccent(strtolower($string));
return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $string))));
}
/**
* Remove all types of spaces.
*
* @param string $string
* @return string
*
* @see https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/String/AbstractUnicodeString.php#L370
*/
public static function trim(string $string): string
{
$chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}";
return preg_replace("{^[$chars]++|[$chars]++$}uD", '', $string);
}
}
<?php
// https://www.php.net/manual/en/datetime.format.php
// Year > DateTime
$year = 2022;
$date = new DateTime(sprintf('%s-01-01 00:00:00', $year));
echo $date->format('Y-m-d H:i:s'); // 2022-01-01 00:00:00
// DateTime > Year
$date = new DateTime('2022-01-01 00:00:00');
echo $date->format('Y'); // 2022
// See the result on
// https://onlinephp.io?s=dY7NCsIwEITvhb7DHpS0YJLaY6r14sEH8NJjsCkt2DQ0keDbu4k_iFjYyywz883uYHqTJpxD75yxgnPvPcMf08rxUeqbvHKleSudcsOoWDfNo3QspmKuUXKGGo5oOKMhTVb38NkDlEVZVqhDFrVW_uPKrJkH7bqMrC0ttnhQFCIe2UBsyHPMqks_QSyg9ZOckYaOtIWTGIQleQU4IYB-Wl7j3jwcGHYujCF_Csgi_guaJg8%2C&v=8.1.10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment