Skip to content

Instantly share code, notes, and snippets.

@broskees
Last active November 1, 2023 21:37
Show Gist options
  • Save broskees/75b25a2057e17948457b634239e4956a to your computer and use it in GitHub Desktop.
Save broskees/75b25a2057e17948457b634239e4956a to your computer and use it in GitHub Desktop.
PHP function to break words on special characters
<?php
if (! function_exists('cleanWordBreaks')) {
function cleanWordBreaks(string $text): string
{
$cleanText = $text;
$cleanup = [];
$makeReplacement = function ($regex, $replacement = '') use (&$cleanup, &$cleanText) {
$cleanText = preg_replace_callback($regex, function ($matches) use (&$cleanup, $replacement) {
if (! empty($replacement)) {
return preg_replace('/' . preg_quote($matches[0], '/') . '/', $replacement, $matches[0]);
}
$placeholder = uniqid();
$cleanup[$placeholder] = $matches[0];
return $placeholder;
}, $cleanText);
};
# Protect special html characters (e.g. &nbsp;)
$makeReplacement('/&[#a-zA-Z0-9]+;/');
# Replace special characters with hidden line breaks
$makeReplacement('/([' . preg_quote('-/&?', '/') . '])/', '$0<wbr>');
# cleanup output
foreach ($cleanup as $placeholder => $original) {
$cleanText = str_replace($placeholder, $original, $cleanText);
}
# preg_ functions return null on error, so return original text if there was an error
return $cleanText ?? $text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment