Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace special characters in a string in PHP using regex except certain chars

Tags:

regex

php

I would like to replace all special characters in a string except space and -.

For example,

Hello-my näme *is (Jämes93!

to

Hello-my name is James93

or even

Hello-my nme is Jmes93

I have the following but it won't work. Pls can someone help? Thanks

preg_replace('#[^\w-]#',"",$string)
like image 242
user1038814 Avatar asked Mar 01 '26 20:03

user1038814


1 Answers

You don't want to use regex for these. You are much better off using iconv() with transliteration:

$result = iconv("UTF-8", "ASCII//TRANSLIT", $text);

This assumes that original string is encoded in UTF-8 and you want to convert it to ASCII which comes close to your question.

You can convert to/from other charsets the same way just as long as you know the original charset.

By the way, you can't do that with preg_replace, it does not support transliteration.

like image 141
Dmitri Snytkine Avatar answered Mar 04 '26 10:03

Dmitri Snytkine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!