简体   繁体   中英

Remove everything but numbers, the letter x, and the plus sign (Regex, PHP)

Many variations of this question exist, and I tried a few generators, but I can't seem to find a regular expression that matches this. Say I have a phone number that looks like "345-324-3243 X039" I want to remove everything but the digits, the letter x and the plus sign (appears in international numbers).

Here is my current non-working regex and code:

$phone = "345-324-3243 X039";
preg_replace('[^\d|x|\+]', '', $phone);

I want it to come out to "3453243243X039" but instead I get "30234-2349".

Lose the | as it is a literal inside a character class, make sure to capture an uppercase "X" (along with a lowercase "x"), use the regex "/quotes/" (otherwise it treats is as "[quotes]") and use the result :

$phone = "345-324-3243 X039";
$phone = preg_replace('/[^\dxX+]/', '', $phone);
// $phone is 3453243243X039

Happy coding.

Remove the | s from your regex and escape the + .

So you're not only getting residual - characters in your results, but entirely different numbers? That's bizarre to me. You can't get 30234-2349 from 345-324-3243 X039 just by deleting characters; the only 0 in that input is right near the end. It's almost like characters are getting shuffled around as well as deleted.

I do notice you don't have regex delimiters around your pattern. I don't even know what the effect of that would be, since I don't recall ever trying it, but that's the only functional problem in your regex. The | s inside your character class will be interpreted as literal | characters, but that shouldn't affect the results for the sample input you posted.

The code I'd use is this:

$phone = preg_replace('/[^\dx+]/i', '', $phone);

I've wrapped the regex in /.../ delimiters, removed the | , unescaped the + (shouldn't have any effect inside a character class), and made it case-insensitive to catch the capital X.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM