PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How to remove all characters except Alphabets, Numbers and Dashes

 November 19, 2022     php, preg-replace, regex, special-characters     No comments   

Issue

I want to remove all characters except Alphabets, Numbers and Dashes. Here is my code

$tracking = "(TCS-123412&2)";
$tracking = preg_replace("/[^ \w]+/", "", $tracking);
echo $tracking;

The output is = TCS1234122

I want the output should be = TCS-1234122

Please help.

Regards


Solution

You need to include all characters which you do not want to exclude in the negative character class. Note that \w also includes underscore, which you presumably want to retain.

$tracking = "(TCS-123412&2)";
$tracking = preg_replace("/[^A-Za-z0-9-]+/", "", $tracking);
echo $tracking;  // TCS-1234122


Answered By - Tim Biegeleisen
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing