Marc Blase

WordPress String Replace

I’ve been working on a site for a fancy client and they need to maintain their brand identity at all costs. So, that means even though their name contains a hyphen, it must NEVER break onto a new line which would split the name.

Tried a couple different methods: javascript and php. Since the site is built in WP I went with the php method. Here it is:

function dont_break_lc($content){
	return str_replace('fancy-name', '<span style="white-space:nowrap">fancy-name</span>', $content);
}
add_filter('the_title', 'dont_break_lc');
add_filter('the_content', 'dont_break_lc');
add_filter('the_excerpt', 'dont_break_lc');

There are still a couple of problems with this solution. str_replace is case dependent so I have to repeat the function for Mixed Case and UPPER CASE occurrences so it shows up as dont_break_Mc() and dont_break_UC() in my functions.php file.

I should add that I settled on the CSS nowrap solution so the site validated. <nobr> is more elegant and works without CSS, but c’mon , who disables CSS these days?

Published on January 4, 2013