By simply making use of PHP's string functions.
<?php
$str='First Name Last Name
Home (123) 345-6789
51 Street Name
City, Pr ABC DEF';
$new_str="";
foreach(explode(PHP_EOL,$str) as $val)
{
if(strpos($val,',')!==false)
{
$val=trim(str_replace(',','',$val)); //<--- For the space thing
$val=explode(' ',$val);
$new_str.=implode('!',$val)."!";
}
else
{
$new_str.=trim($val)."!"; //<--- Added here
}
}
echo $new_str;
OUTPUT :
First Name Last Name!Home (123) 345-6789!51 Street Name!City!Pr!ABC!DEF!