Removing Independent Numbers Using PHP Regular Expression

How can I remove independent numbers in a string in PHP using regular expressions?

Examples:

  • "hi123" should not be changed.

  • "hi 123" should be converted to "hi " .

+4
source share
4 answers

Use the pattern \b\d+\b , where \b matches the word boundary. Here are some tests:

 $tests = array( 'hi123', '123hi', 'hi 123', '123' ); foreach($tests as $test) { preg_match('@\b\d+\ b@ ', $test, $match); echo sprintf('"%s" -> %s' . "\n", $test, isset($match[0]) ? $match[0] : '(no match)'); } // "hi123" -> (no match) // "123hi" -> (no match) // "hi 123" -> 123 // "123" -> 123 
+2
source

In Ruby (PHP is probably close), I would do this with

 string_without_numbers = string.gsub(/\b\d+\b/, '') 

where the part between // is a regular expression, and \b indicates the word boundary. Note that this would turn "hi 123 foo" into "hi foo" (note: there must be two spaces between words). If words are separated by spaces, you can use

 string_without_numbers = string.gsub(/ \d+ /, ' ') 

which replaces each sequence of numbers surrounded by two spaces, one space. This may leave numbers at the end of the line, which may not be what you intend.

+1
source
 preg_replace('/ [0-9]+( |$)/S', ' ', 'hi 123 aaa123 123aaa 234'); 
0
source
 preg_replace('/ [0-9]+.+/', ' ', $input); 
0
source

All Articles