Last active
November 1, 2023 21:37
-
-
Save broskees/75b25a2057e17948457b634239e4956a to your computer and use it in GitHub Desktop.
PHP function to break words on special characters
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 | |
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. ) | |
$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