Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to remove extra whitespace from a string in PHP

1 Answer

0 votes
/**
 * Normalizes a string by trimming leading and trailing whitespace
 * and collapsing multiple consecutive spaces into a single space.
 *
 * @param string $input
 * @return string
 */
function removeExtraWhitespace(string $input): string
{
    // Step 1: Use regular expression \s+ to match one or more contiguous whitespace characters
    // (spaces, tabs, newlines) and replace each group with a single space.
    $collapsed = preg_replace('/\s+/', ' ', $input);

    // Step 2: Strip any leading or trailing whitespace left at the boundaries of the string.
    return trim($collapsed);
}

// Input string containing variable padding and extra internal spaces
$s = "   This   is   a   test   string   with         extra   spaces.   ";

// Clean and normalize the string
$cleanedString = removeExtraWhitespace($s);

echo $cleanedString . PHP_EOL;


/*
run:

This is a test string with extra spaces.

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
...