Avatar ·

How to remove all spaces from a string in PHP? Complete guide

Hello everyone! I'm a beginner in PHP and I've encountered a task: I need to remove all spaces from a string. For example, I have the string "Привет, мир! Как дела?", and I need to get "Привет,мир!Какдела?".\n\nI've tried several options, but none work as needed. First, I tried trim() — it only removes spaces at the beginning and end of the string, but not inside. Then I tried str_replace(' ', '', $string) — it seems to work, but only with regular spaces. What about tabs, line breaks, and other whitespace characters? Is there a universal way?\n\nHere's an example of my code:\n\n```php\n$string = " Привет, мир! Как дела? ";\necho str_replace(' ', '', $string); // Outputs "Привет,мир!Какдела?" — almost what I need\n```\n\nBut if the string contains tabs or non-breaking spaces...