user3736833 user3736833 - 7 months ago 21
PHP Question

PHP: how to remove special char(except some) from string

Hello i tried below code using regex

$str = preg_replace("/[^a-z0-9_]/i", '', 'New_text % *');

//output => New_text

( _ is except char )

all work perfect but when my input string something like in other language(ex Hindi), char in Hindi Lang will
also delete.

same as above example

$str = preg_replace("/[^a-z0-9_]/i", '', 'कपिल शर्मा % * _');

//output => _

how to get: कपिल शर्मा _

is there any mistake in regex or any other way in PHP we can do?


Use unicode properties:

$str =  preg_replace("/[^\p{L}\p{N}\p{Z}_]/u", '', 'कपिल शर्मा % * _');


  • \p{L} stands for any letter in any language
  • \p{N} stands for any digit in any language
  • \p{Z} stands for any kind of separator.
  • u flag for unicode