2011-07-17 75 views

回答

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

这可能不会像'嗨123abc'的输入做预期的事情。 – Mat

+0

现在应该没问题了,我错过了一些应该在最后的东西:) – user841092

1

在Ruby(PHP可能接近),我会

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

做到哪里//之间的部分是正则表达式和\b指示文字边界。请注意,这会将"hi 123 foo"转换为"hi foo"(注意:单词之间应该有两个空格)。如果语言只用空格分开,你可以选择使用

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

它取代的两个空格用一个空格包围位数每个序列。这可能会在字符串末尾留下数字,这可能不是您想要的。

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

使用模式\b\d+\b其中\b与字边界匹配。这里有一些测试:

$tests = array(
    'hi123', 
    '123hi', 
    'hi 123', 
    '123' 
); 
foreach($tests as $test) { 
    preg_match('@\b\d+\[email protected]', $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 
相关问题