使用PHP正则表达式删除独立数字

使用PHP正则表达式删除独立数字,php,regex,Php,Regex,如何使用正则表达式删除PHP中字符串中的独立数字 示例: 不应修改hi123 hi 123应转换为hi 在Ruby中,PHP可能很接近,我会使用 string_without_numbers = string.gsub(/\b\d+\b/, '') 其中//之间的部分是正则表达式,而\b表示单词边界。注意,这将把hi 123 foo变成hi foo注意:单词之间应该有两个空格。如果单词之间只有空格,您可以选择使用 string_without_numbers = string.gsub(/ \

如何使用正则表达式删除PHP中字符串中的独立数字

示例:

不应修改hi123

hi 123应转换为hi


在Ruby中,PHP可能很接近,我会使用

string_without_numbers = string.gsub(/\b\d+\b/, '')
其中//之间的部分是正则表达式,而\b表示单词边界。注意,这将把hi 123 foo变成hi foo注意:单词之间应该有两个空格。如果单词之间只有空格,您可以选择使用

string_without_numbers = string.gsub(/ \d+ /, ' ')
它将由两个空格包围的每个数字序列替换为一个空格。这可能会在字符串末尾留下数字,这可能不是您想要的。

使用模式\b\d+\b,其中\b与单词边界匹配。以下是一些测试:

preg_replace('/ [0-9]+.+/', ' ', $input);
$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

这可能无法实现“hi 123abc”等输入的预期效果。现在应该可以了,我错过了一些应该在结尾的内容:
$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