Remove Widows and Orphans in Text Using PHP/Smarty

This script accepts a string and then places a non-breaking space between the last two words.

Passing the string to the script:
{include file=”widow.tpl” string_to_widow=$string.to.widowize}

Script:
{assign var=’string_to_widow’ value=$string_to_widow}

{php}
$original_string = $this->get_template_vars(‘string_to_widow’);

$original_string = str_replace(‘$’,’dollar’, $original_string);
$original_string = str_replace(‘%’,’percent’, $original_string);
$original_string = str_replace(‘.’,’period’, $original_string);

$array_string = str_word_count($original_string, 1, ‘1,2,3,4,5,6,7,8,9,0’);

$array_count = count($array_string);

$widow_string = $array_string[$array_count-2] . ” ” . $array_string[$array_count-1];

foreach ($array_string as $k => $v) {
if ($k != $array_count-2 && $k != $array_count-1) {
$final_string = $final_string . $v . ” “;
}
else if ($k == $array_count – 1) {
$final_string = $final_string . $widow_string;
}
}

$final_string = str_replace(‘dollar’,’$’, $final_string);
$final_string = str_replace(‘percent’,’%’, $final_string);
$final_string = str_replace(‘period’,’.’, $final_string);

$this->assign(‘widow_string’,$final_string);

{/php}

{$widow_string}


Subscribe to comments Comment | Trackback |
Post Tags: ,

Browse Timeline


Comments ( 2 )

Create modifier is better solution for this problem:

Cheers!

Kowal added these pithy words on Feb 04 13 at 11:13 am


function smarty_modifier_orphan($string)
{
return preg_replace('/\s([a-zA-Z]{1,2})\s/', ' $1 ', $string);
}

Kowal added these pithy words on Feb 04 13 at 11:14 am

Add a Comment

You must be logged in to post a comment.


© Copyright 2009-2010 Alpha Papa Hotel . Thanks for visiting!