Preg_replace in PHP - regular expression for NOT condition

I am trying to write a function in PHP using preg_replace where it will replace all those characters that are NOT found in the list. Usually we replace the place where they are found, but this is different.

For example, if I have a line:

$mystring = "ab2c4d";

I can write the following function, which will replace all numbers with *:

preg_replace("/(\d+)/","*",$mystring);

But I want to replace those characters that are neither a number nor the alphabets from a to z. They may be similar to # $ * (); ~! {} [] | \ /., <>? 'etc

So nothing but numbers and alphabets should be replaced by something else. How to do it?

thank

+9
source share
6 answers

( ^ ):

/[^\da-z]+/i

: , , , , ;)

+18

" " . - [^...]. [^\w] .

+5

Try

preg_replace("/([^a-zA-Z0-9]+)/","*",$mystring);
+4

\W -- . _ - , .

preg_replace("/\W/", "something else", $mystring);

, , . ,

preg_replace("/[\W_]/", "something else", $mystring);
+2

\d, \w regex , .

So \w (.. -), \w -, , , -.

, .

regular-expressions.info.

+1

PHP 5.1.0 \p{L} ( Unicode) \p{N} ( Unicode), Unicode, \d \w

preg_replace("/[^\p{L}\p{N}]/iu", $replacement_string, $original_string);

/iu :

i (PCRE_CASELESS)

u (PCRE_UTF8) : https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

0

All Articles