How to split a long word/string into multiple lines with PHP

So when creating this simple website I ran into a problem with this blog post:

http://dtbaker.net/web-development/13-permission-denied-var-www-vhosts-site-com-httpdocs-htaccess-pcfg_openfile-unable-to-check-htaccess-file-ensure-it-is-readable/

It had a very long “word” in the title of the blog post: /var/www/vhosts/site.com/httpdocs/.htaccess

This caused the word to spill over outside the boundary of the blog box.

A CSS fix (word-break:break-all); did not work because all words for all blog posts were split at random points which made reading very hard.

So the solution was to split any long titles in PHP and put in the wonderful <wbr> html code.

The original PHP code in the WordPress template:

<h4 class="entry-title">
 <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'mistcrm' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
 </h4>

The new PHP code in the WordPress template:

<h4>
 <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'mistcrm' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php 
 $title = get_the_title(); // get the title of this WP post into $title variable
 echo preg_replace('/([^\s]{22})/', '$1<wbr>', $title); // split any long strings (longer than 22 characters) with a special <wbr> html character.
 ?></a>
 </h4>

So the code without WordPress would look like:

$string = "a bunch of text with a few reaaaaallllllllllllllyyyyyyyyyyyyy llllllloooooooooooooonnnnnnnnnnnnnnnnnnngggggggggggggggg strings in it";
$word_break_result = preg_replace('/([^\s]{22})/', '$1<wbr>', $string);

 

Leave a Reply

Your email address will not be published. Required fields are marked *