Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5755
  • Last Modified:

Regular Expressions - Remove all non-alpha except replace * with %

I want to remove all (multiple) non-alpha characters in $string, except that I want to replace all occurences of '*' with a '%'

For example '1234-56.*.90*' would be changed to '123456%90%'

Needs to be a PHP function (PHP v4.4.x)


Calvin

0
Calvin Close
Asked:
Calvin Close
1 Solution
 
aminerdCommented:
// remove non-alpha-numeric characters (except %)
$string = preg_replace('/[^a-zA-Z0-9*]/', '', $string);

// replace % with *
$string = str_replace('*', '%', $string);
0
 
aminerdCommented:
(My last comment is actually backwards.. I'm replacing * with %)
0
 
TeRReFCommented:
A tiny bit shorter would be
$string = preg_replace('/([^\w\d*])/', '', $string);
$string = str_replace('%', '*', $string);
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
RoonaanCommented:
@TeRReF: \w = \d | [a-z][A-Z] | _

$string = str_replace('*','%', preg_replace('/[^\d\*]/','',$string));

-r-
0
 
aminerdCommented:
Roonaan, won't [^\d\*] replace any alpha characters?
0
 
ixtiCommented:
calvinclose if you need to strip up speces too, then aminerd's solution is for you.
TeRReF's solution is actually not what you need, because \w includes underscope "_" and as I understood you don't want them.

So:
<?php
// if you want to strip spaces
$string = preg_replace('/[^a-z0-9*]/i', '', $string);

// if you don't, then comment string above and uncomment this string:
// $string = preg_replace('/[^a-z 0-9*]/i', '', $string);

$string = str_replace('*', '%', $string);
?>
0
 
ixtiCommented:
Sorry, when Iv'e opened a question, there were no Roonaan's solution.
Roonaan's solution is great, and if you want to add alpha chars to you can simply add a-z to regular expression of Roonaan:
$string = str_replace('*','%', preg_replace('/[^a-z\d\*]/i','',$string));
0
 
Calvin ClosePresidentAuthor Commented:
I have accepted aminerd's solution because it did exactly what I wanted - remove all occurences of chars that are not (A-Z, a-z or *), then replace * with %.

I apologise if some of the other fancier solutions do the same thing - I am a novice at regular expressions, so chose the first solution that met my requirements.

Thanks Everyone,


Calvin
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now