How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
php
regex
Answers
2
This:
preg_replace("[a-zA-Z0-9_-]", "", $var);
wouldn't even replace those characters, except if the input string is exactly the pattern. By using []
as delimiters, they have not the same effect as their would in the expression itself. You could change your delimiter (e.g.: /
), or add some more brackets in the pattern:
preg_replace("/[a-zA-Z0-9_-]/", "", $var); // this works
preg_replace("[[a-zA-Z0-9_-]]", "", $var); // this too
Now, to negate a pattern in []
, you use ^
at the beginning:
preg_replace("/[^a-zA-Z0-9_-]/", "", $var);
You could also have used the insensitive modifier i
to match both lowercase (a-z
) and uppercase (A-Z
):
preg_replace("/[^a-z0-9_-]/i", "", $var); // same as above
Monday, December 26, 2022
5
The Arabic regex is:
[u0600-u06FF]
Actually, ?-?
is a subset of this Arabic range, so I think you can remove them from the pattern.
So, in JS it will be
/^[a-z0-9+,()/'su0600-u06FF-]+$/i
See regex demo
Tuesday, October 11, 2022
3
For this PHP regex:
$str = preg_replace ( '{(.)1+}', '$1', $str );
$str = preg_replace ( '{[ '-_()]}', '', $str )
In Java:
str = str.replaceAll("(.)\1+", "$1");
str = str.replaceAll("[ '-_\(\)]", "");
I suggest you to provide your input and expected output then you will get better answers on how it can be done in PHP and/or Java.
Sunday, October 9, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
php
regex
You can test your string (let
$str
) usingpreg_match
:If you need more symbols you can add them before
]