3

I need a regex to remove the digits from a string but not also the spaces. I currently have

$city_location = 'UK,0113|Leeds new york';
$sip_city = '0113Leeds new york';
 $city = preg_replace('/[^a-z]/i', '', $sip_city);

It removes the digits but also the spaces so I need a regex which won't remove the spaces.

2 Answers 2

13

Use \d if you want to remove all digits

$city = preg_replace('/\d/', '', $sip_city);

Or [^a-z\s] if you want to replace all except alphabets and whitespaces

$city = preg_replace('/[^a-z\s]/i', '', $sip_city);
Sign up to request clarification or add additional context in comments.

3 Comments

I think you don't need the i flag here :)
Michael just wants to remove the digits but your code would remove special charactes like $,@,# or others. what it wont remove is letters of the alphabet and spaces.what do u say about my quote below
@lovesh, my first solution will only remove digits.
3

use

$city = preg_replace('/[0-9]/', '', $sip_city);

in your code the regex engine doesnt match anything that is not in the alphabet that is A-Z and a-z. so spaces are not in the alphabet and they get matched. i dont have much experience with regex but one thing which i have understood is that

it is better to tell the regex engine what u want rather than telling what u dont want

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.