Reputation: 49
How can I remove independent numbers in a string in PHP using regular expressions?
Examples:
"hi123"
should not be modified.
"hi 123"
should be converted to "hi "
.
Upvotes: 4
Views: 129
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
Reputation: 156
preg_replace('/ [0-9]+( |$)/S', ' ', 'hi 123 aaa123 123aaa 234');
Upvotes: 0
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