4

Lets say I have a word like this "I shoot someone using ak47 and m4s 32 times" What is the best way to remove pure number number so that I only get "I shoot someone using ak47 and m4s times" I will be really glad if someone can teach me how to do that.

Ankit Shubham
  • 2,989
  • 2
  • 36
  • 61
Ryan Arief
  • 983
  • 2
  • 16
  • 36
  • Possible duplicate of [How to remove all numbers from string?](http://stackoverflow.com/questions/14236148/how-to-remove-all-numbers-from-string) – Tom Apr 16 '16 at 12:25
  • 3
    This is not a duplicate, he tries to remove only pure numbers, not numbers with text like ak47 ... – Black Apr 16 '16 at 12:28

2 Answers2

5

You could do that with a regex checking for word boundaries and digits:

/\b\d+\b/

Here you are checking for a word-boundary, followed by any number of digits followed by another word boundary. The forward slashes are the delimiters.

Then you can use for example preg_replace to replaced the matched numbers with an empty string:

$result = preg_replace('/\b\d+\b/', '', $your_string);

Note that you will end up with 2 spaces between m4s and times but you will not see that in html output. If necessary, you can search for these as well.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1
function remove_numbers($string) {
    $num = array(0,1,2,3,4,5,6,7,8,9);
    return str_replace($num, null, $string);
}
Shubham Dixit
  • 106
  • 10
  • 1
    You could use [range](http://php.net/range) (i.e. `range(0, 9)`) rather than using a hardcoded array. – ajshort Apr 17 '16 at 12:51