Avatar ·

How to remove all non-alphanumeric characters from a string in PHP?

Hi everyone! I'm new to PHP and ran into this problem: I need to clean a string from everything except letters (Latin and Cyrillic) and digits. I tried using str_replace — it turned out terribly cumbersome, I had to list each character. Here's what I tried to do:\n\n```php\n$text = "Привет, мир! Как дела? 123.";\n$clean = str_replace(array(',', '!', '?', '.', ' '), '', $text);\necho $clean; // ПриветмирКакдела123\n```\n\nBut this is not serious — listing all possible punctuation marks, spaces, and other junk manually. What if there are brackets, slashes, or special characters like @#$%? Besides, the user can input anything.\n\nI've heard that you can use regular expressions with preg_replace, but I don't understand what pattern to set. I need only the following to remain:\n- Latin alphabet letters (a-z, A-