Replace characters in variable

How can the following be implemented?
There is a variable that contains, for example, the following text “privet-hash-code;“. This variable must be checked with such a regular expression “[^\a-zA-Z0-9]” (the text of the variable no longer fits this rule). So, how to make it so that if the text of the variable does not fit, then the characters that should not be are simply removed?
Those. was “privet-hash-code;” and should become “privethashcode“.

Thank you.

Answer 1, authority 100%

I hope I understood you correctly.

You can separately store 2 versions of the regular expression – to check the validity of the entire textand to check the validity of one character.

In case check(string, __)says that stringdoes not match __, then we do strip(string, __), i.e. we remove those characters that do not fall under it .
The second part, by the way, can be optimized if you don’t want to deal with regular expressions for a single character.

If you are talking about a more general task – how to arbitrarily taken expressionthrough a finite number of changes to bring the form of some regexp'(or tell what the mapping is impossible), then this is a topic for a separate article in ACM Digital Library.

Here you can try to build some finite state machine or a suffix tree and take the Levenshtein distance as a metric, but before doing this, you should search Google for the relevant articles.

The point is that there is probably no standard means for option number 2.

Answer 2, authority 50%

You can do this:

$var = 'privet-hash-code;';
$result = '';
preg_match('/([a-zA-Z0-9]+)/', $var, $matches);
    $result = implode('', $matches[1]);