Last active
May 10, 2021 20:57
-
-
Save oliveratgithub/36b9c0b02391896604033097a1b31ac4 to your computer and use it in GitHub Desktop.
PHP Regex to output SEO optimized «meta title» and «meta description» with valid characters only and utf8 support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** Raw content input */ | |
$title = 'Begriff "Test"; zu weiteren gleichnamigen Bedeutungen siehe Test <Begriffsklärung>'; | |
$description = 'Das Wort „Test“ kommt vom altfranzösischen test: Tiegel‚ Topf für alchemistische Versuche bzw. lateinisch testum, zu: testa = Platte, Deckel; (Ton)schale, Scherbe.'; | |
/** SEO friendly content */ | |
$seo_allowed_chars_pattern = '([^\w\s\p{L}.,;:!?\-\/\(\)\[\]…«»#@])'; | |
$meta_title = mb_ereg_replace($seo_allowed_chars_pattern, '', $title); | |
$meta_description = mb_ereg_replace($seo_allowed_chars_pattern, '', $description); | |
/** | |
* Result | |
* [$meta_title] Begriff Test; zu weiteren gleichnamigen Bedeutungen siehe Test Begriffsklärung | |
* [$meta_description] Das Wort Test kommt vom altfranzösischen test Tiegel Topf für alchemistische Versuche bzw. lateinisch testum, zu testa Platte, Deckel; (Ton)schale, Scherbe. | |
*/ | |
var_dump($meta_title); | |
var_dump($meta_description); | |
/** SEO friendly lengths */ | |
$meta_title = mb_substr($meta_title, 0, 60, 'utf8'); // max 60 chars | |
if (mb_strlen($meta_title, 'utf8') >= 60) $meta_title = mb_substr($meta_title, 0, 57, 'utf8') . '...'; | |
$meta_description = mb_substr($meta_description, 0, 155, 'utf8'); // max 155 chars | |
if (mb_strlen($meta_description, 'utf8') >= 60) $meta_description = mb_substr($meta_description, 0, 153, 'utf8') . '...'; | |
/** | |
* Result | |
* [$meta_title] Begriff Test; zu weiteren gleichnamigen Bedeutungen siehe... | |
* [$meta_description] Das Wort Test kommt vom altfranzösischen test Tiegel Topf für alchemistische Versuche bzw. lateinisch testum, zu testa Platte, Deckel; (Ton)schale, Sche... | |
*/ | |
var_dump($meta_title); | |
var_dump($meta_description); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment