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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

How to remove the middle word from a string in PHP

2 Answers

0 votes
$str = "php c c++ java rust";
 
// Split the string into words
$words = explode(' ', $str);
 
// Calculate the middle index
$midIndex = floor(count($words) / 2);
 
// Create a new string without the middle word
$result = implode(' ', 
            array_merge(array_slice($words, 0, $midIndex), array_slice($words, $midIndex + 1)));
 
echo $result;
 
  
  
/*
run:
  
php c java rust
  
*/

 



answered Dec 3, 2024 by avibootz
edited Dec 24, 2025 by avibootz
0 votes
function removeMiddleWord(string $str): string {
    // Split into words (handles multiple spaces)
    $words = preg_split('/\s+/', trim($str));

    // If fewer than 3 words, nothing to remove
    if (count($words) <= 2) {
        return $str;
    }

    // Middle index
    $mid = intdiv(count($words), 2);

    // Remove the middle word
    unset($words[$mid]);

    // Reindex and join
    return implode(' ', array_values($words));
}

$str = "c# c c++ java rust";

echo removeMiddleWord($str);  




/*
run:

c# c java rust

*/

 



answered Dec 24, 2025 by avibootz
...