PHP preg_replace

Posted on 2010-11-16
Last Modified: 2012-05-10

I currently have this line of code which cleans a string. Could someone tell me how I would change this to allow the minus sign (-)?

$string = preg_replace("/[^a-zA-Z0-9s]/", "", $string);

Question by:SheppardDigital
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 31

Expert Comment

by:Marco Gasi
ID: 34144520
Try this:

$string = preg_replace("/[^a-zA-Z0-9s][^-]/", "", $string);

LVL 14

Expert Comment

ID: 34144529

$string = preg_replace("/[^a-zA-Z0-9s\-]/", "", $string);

Open in new window

LVL 31

Expert Comment

by:Marco Gasi
ID: 34144544
Ooops, I was confused! :-(
LVL 13

Accepted Solution

dsmile earned 500 total points
ID: 34144605
I think there's no needs to escape - in that expression.

$string = preg_replace("/[^a-zA-Z0-9s-]/", "", $string);

is enough.

@SheppardDigital: here's a nice tutorrial about regular expression which might help you in the future

Expert Comment

ID: 34144621
$string = preg_replace("/[^a-zA-Z0-9s\-]/", "", $string);

Open in new window


Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to implement server side field validation and display customized error messages to the client.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question