Testuser075
Testuser075

Reputation: 77

include quantifier in character class

How am I able to add a quantifier inside a character class? This is my current regular expression and what I want to achieve (besides what it is doing right now) is that whitespaces and dots (with an oncurrence of more than 2) will be matched and finally be removed using the preg_replace function

Current regular expression:

[^A-Za-z0-9\s.\'\(\)\-\_]

Desired solution (notice the quantifier {1}):

[^A-Za-z0-9\s{1}.{1}\'\(\)\-\_]

Input (that has to be filtered):

Hi, this is a text.......that has    to be filtered!@#!

Output (After the regular expression):

Hi this is a textthat hasto be filtered

Upvotes: 0

Views: 447

Answers (2)

Sebastian Proske
Sebastian Proske

Reputation: 8413

There is no possibility for a quantifier inside a character class. However you could use alternation and normal quantifiers, like

$str = "Hi, this is a text.......that has    to be filtered!@#!";
$pattern = "/[^A-Za-z0-9\\s.'()_-]|\\.{3,}|\\s{3,}/";
$subst = "";
print(preg_replace($pattern, $subst, $str));

Outputs: Hi this is a textthat hasto be filtered

You could also shorten the character class to [^\\w\\s.'()-]

In the regex [^A-Za-z0-9\\s.'()_-] matches any character that is not alphanumeric or whitespace or dot or round bracket or apostrophe or underscore or minus. \\.{3,} matches any dot with a occurance of 3 or more (more than 2). \\s{3,} matches any whitespace with a occurance of 3 or more (more than 2) - note that this will match e.g. blank tab blank, as these are all whitespace characters.

With the empty string substitution, everything matched will be replaced by an empty string (thus removed).

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Another solution using preg_replace_callback function:

$str = "Hi, this is a text.......that has    to be filtered!@#!";

$replaced = preg_replace_callback(
        ["/(\s{3,}|\.{3,})/" , "/[^A-Za-z0-9\s.'()_-]/" ],
        function($m) { return ""; },
        $str);

print_r($replaced);

The output:

Hi this is a textthat hasto be filtered

Upvotes: 0

Related Questions