Reputation: 107
How would you strip spaces between one letter words. Example:
If possible preg_replace solution, sorry for not telling before.
Upvotes: 2
Views: 551
Reputation: 786291
Try this php code:
<?php
$str = "T I G R U S FOO and Drezga d . o . o . New York";
$out = preg_replace('~(\b.)\s~', "\\1", $str);
var_dump($out);
?>
OUTPUT
string(38) "TIGRUSFOO and Drezga d. o. o. New York
<?php
$str = "T I G R U S FOO and Drezga d . o . o . New York N Y";
$s = preg_replace('~((?<=^[^\s])|(?<=\s[^\s]))\s(?=[^\s](\s|$))~', "", $str);
var_dump($s);
?>
OUTPUT
string(40) "TIGRUS FOO and Drezga d.o.o. New York NY"
?>
Upvotes: 2
Reputation: 475
That's not possible, unfortunately. There is no easy way to distinguish single-space word boundaries from extraneous single-spaces between a word's characters.
EDIT: Retracted -- I made the assumption that the replacement would need to properly handle (i.e. keep separate) words that are actually one character long.
Upvotes: 0
Reputation: 84190
The following works.
$string = "T I G R U S FOO and Drezga d . o . o . New York";
$words = explode(" ", $string);
$output = array();
$temp_word = "";
foreach($words as $word)
{
if (strlen($word) == 1)
{
$temp_word .= $word;
}
else
{
if ($temp_word != "")
{
$output[] = $temp_word;
$temp_word = "";
}
$output[] = $word;
}
}
$output = implode(" ", $output);
echo $output;
Outputs: "TIGRUS FOO and Drezga d.o.o. New York"
Upvotes: 3