Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove numbers from a string with RegEx

Tags:

string

regex

php

I have a string like this:

" 23 PM"

I would like to remove 23 so I'm left with PM or (with space truncated) just PM.

Any suggestions?

Needs to be in PHP

like image 858
Ali Avatar asked Jul 29 '10 13:07

Ali


People also ask

How extract all numbers from string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

How do I remove numbers from an alphanumeric string in Python?

In Python, an inbuilt function sub() is present in the regex module to delete numbers from the Python string. The sub() method replaces all the existences of the given order in the string using a replacement string.


2 Answers

echo trim(str_replace(range(0,9),'',' 23 PM'));
like image 191
Mark Baker Avatar answered Sep 30 '22 14:09

Mark Baker


Can do with ltrim

ltrim(' 23 PM', ' 0123456789');

This would remove any number and spaces from the left side of the string. If you need it for both sides, you can use trim. If you need it for just the right side, you can use rtrim.

like image 42
Gordon Avatar answered Sep 30 '22 15:09

Gordon