user848491
user848491

Reputation: 49

Remove independent numbers using a PHP regular expression

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

Examples:

Upvotes: 4

Views: 129

Answers (5)

Nikhil Jaitak
Nikhil Jaitak

Reputation: 131

use this regex : regex='\s\d+'

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272106

Use the pattern \b\d+\b where \b matches a 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

Upvotes: 2

user841092
user841092

Reputation: 156

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

Upvotes: 0

Scott C Wilson
Scott C Wilson

Reputation: 20016

preg_replace('/ [0-9]+.+/', ' ', $input);

Upvotes: 0

Confusion
Confusion

Reputation: 16841

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

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

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

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

which replaces every sequences of digits surrounded by two spaces with a single space. This may leave numbers at the end of a string, which may not be what you intend.

Upvotes: 1

Related Questions