note 105644 deleted from function.wordwrap by danbrown

From: Date: Sat, 03 Sep 2011 14:16:29 +0000
Subject: note 105644 deleted from function.wordwrap by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-182920@lists.php.net to get a copy of this message
Note Submitter: dev dot ivangc at gmail dot com ---- This code extends wordwrap functionality to insert the <wbr /> tag inside a html text every 10 characteres per word without break it. The function works with utf-8 encoding: <?php function insertWbr($text) { $pat = '/>([^<>]*?)([^\s<]{11,}?)(<|\z|\s)/'; return preg_replace_callback($pat, 'insertWbrCallback', $text); } function insertWbrCallback($matches){ $longWord = $matches[2]; $len = mb_strlen($longWord, 'UTF-8'); $lastBreak = 0; $newString = ''; for($i=0; $i<$len; $i++){ if( ($i+1) % 10 == 0){ $newString .= mb_substr($longWord, $lastBreak, 10, 'UTF-8'); $newString .= '<wbr />'; $lastBreak = $i+1; } } $newString .= mb_substr($longWord, $lastBreak, 10, 'UTF-8'); return '>'.$matches[1].$newString.$matches[3]; } ?> How to use: <?php echo insertWbr('<p><a href="example.com/foo/bar">example.com/foo/bar</a></p>'); ?> Output: <p><a href="example.com/foo/bar">example.co<wbr />m/foo/bar</a></p>

« previous php.notes (#182920) next »