Jump to content

Recommended Posts

We  have some blocks of text  that  have paragraphs and then sometoimes there

are  long stretches of  blanks  between  words. How do we set up a pattern match so that it will  remove  all  the blanks after the first?, that is, if I have

10 blank spaces,  I want to  remove nine blanks.

 

Thanks,

 

Natalie

Link to comment
https://forums.phpfreaks.com/topic/59150-text-formatting/
Share on other sites

If it's only text and spaces, this might work.

<?php
$string = "hello world            4   3     56            hi";
$explode = explode(" ", $string);
$implode = implode(" ", $explode);
echo $implode; //outputs "hello world 4 3 56 hi"
?>

 

That will just make a list of everything between the space characters (whereby deleting all of them) and then reforming the entire string so that all elements have one space between them.

Link to comment
https://forums.phpfreaks.com/topic/59150-text-formatting/#findComment-293768
Share on other sites

@Charlieholder

 

Tested that before posting, mine ran faster (~194-200% faster.. 2x). Also, afterward, the modified string still contained multiple spaces.

 

Oh, if php version < 5.0.0

 

<?php
function str_multspace_del($str)
{
    $cnt = 0;
    do {
        $ls = strlen($str);
        $str = str_replace('  ', ' ', $str);
    } while( $ls != strlen($str) );
    
    return $str;
}

?>

Link to comment
https://forums.phpfreaks.com/topic/59150-text-formatting/#findComment-293783
Share on other sites

try

<?php
$string = "hello 	world            4   3     56  	         


hi";
echo $string1 = preg_replace('/[\s]+/',' ',$string); //remove spaces, tabs new line  
//or
echo "<br />\n";

echo $string2 = preg_replace('/[ ]+/',' ',$string); // remove just spaces
?>

Link to comment
https://forums.phpfreaks.com/topic/59150-text-formatting/#findComment-293810
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.