-1

I would like to replace all characters in a string other than [a-zA-Z0-9\-] with a space.

I've found this post and no matter how many times I tweak the REGEX, I can't get it to "don't match [a-zA-Z0-9-], only match and replace other characters".

At the moment, I have the following:

$original_name = trim(' How to get file creation & modification date/times in Python?  ');

$replace_strange_characters = preg_replace("/^((?!([a-zA-Z0-9\-]+)*))$/", " ", $original_name);

// Returns: How to get file creation & modification date/times in Python?
echo $replace_strange_characters;

I wish for it to replace all of the strange characters with a space ' ', thus returning:

How to get file creation   modification date times in Python?

I'm really struggling with these "don't match" scenarios.

Here's my code so far: http://tehplayground.com/#2NFzGbG7B

Community
  • 1
  • 1
Luke
  • 21,545
  • 28
  • 103
  • 186
  • I wish to retain dashes, using `\w` as suggested in the answers for that question would not have the desired effect. :( – Luke Oct 25 '13 at 16:17

3 Answers3

2

You may try this (You mentioned you want to keep dash)

$original_name = trim(' How to get file creation & modification date/times in Python?  ');
$replace_strange_characters = preg_replace('/[^\da-z-]/i', ' ', $original_name);
echo $replace_strange_characters;

DEMO.

The Alpha
  • 138,380
  • 26
  • 281
  • 300
0

Wouldn't this regex do it?

[^a-zA-Z0-9\-]

Oh, and why are you doing this btw?

Horse SMith
  • 963
  • 2
  • 11
  • 24
0

Try this

$replace_strange_characters = preg_replace("([^a-zA-Z0-9\-\?])", " ", $original_name);

The previous answer strip out the ?

Jorge Campos
  • 21,622
  • 7
  • 56
  • 84