Question

I use the following for a preg_replace:

$replace = '/[!\/."",#\s\-:?"]+/';

For example when I try and add ' above it gives me an error on the file:

Parse error: syntax error, unexpected T_NS_SEPARATOR in .../s.php on line 38

Additionally, is there an easier way to list all of the symbols to be replaced?

Was it helpful?

Solution

If you want to get rid of any symbol, try:

$replace = "/[^a-zA-Z0-9 ]/";

The ^ indicates "anything but the following". Add whatever characters you want to allow to the list. It's easier than listing every symbol and having to deal with escaping.

OTHER TIPS

You need to escape the ' character as it's also the delimiter of the single quoted string:

$replace = '/[!\/.,#\s\-:?"\']+/';
                           ^^

Escaping is done by adding \ in front of it. This is normally logical as you otherwise would have finished the string definition which then leads to a syntax error (PHP is not able to parse your code). See Single quoted String­Docs.

Is there an easier way to list all of the symbols to be replaced?

Isn't it easy enough to just list them (as you already do)? So I must admit it's not clear to me what you're actually concerned about so I can't offer something more easy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top