Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
preg_replace to remove all characters except dashes, letters, numbers, spaces, and underscores

I need to remove all characters in a string except dashes, letters, numbers, spaces, and underscores.

Various answers on SO come tantalizingly close (Replace all characters except letters, numbers, spaces and underscores, Remove all characters except letters, spaces and apostrophes, etc.) but generally don't include dashes.

Help would be greatly appreciated.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could do something like below:

    $string = ';")<br>kk23how nowbrowncow_-asdjhajsdhasdk32423ASDASD*%$@#!^ASDASDSA4sadfasd_-?!'; 
    $new_string = preg_replace('/[^ \w-]/', '', $string);
    echo $new_string;
  • [^] represents a list of characters NOT to match
  • \w is a short for word character [A-Za-z0-9_]
  • - matches a hyphen literally
about 4 years ago · Santiago Trujillo Report

0

You probably need something like:

$new = preg_replace('/[^ \w-]/', '', $old);

Explanation:

[^ \w-]

Match any single character NOT present in the list below «[^ \w-]»
   The literal character “ ” « »
   A “word character” (Unicode; any letter or ideograph, any number, underscore) «\w»
   The literal character “-” «-»

Demo

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!