简体   繁体   English

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

[英]Remove independent numbers using a PHP regular expression

How can I remove independent numbers in a string in PHP using regular expressions?如何使用正则表达式删除 PHP 中字符串中的独立数字?

Examples:例子:

  • "hi123" should not be modified. "hi123"不应被修改。

  • "hi 123" should be converted to "hi " . "hi 123"应转换为"hi "

Use the pattern \b\d+\b where \b matches a word boundary.使用模式\b\d+\b其中\b匹配单词边界。 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

In Ruby (PHP is probably close), I would do it with在 Ruby (PHP 可能接近),我会这样做

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

where the part between // is the regex and \b indicates a word boundary.其中//之间的部分是正则表达式, \b表示单词边界。 Note that this would turn "hi 123 foo" into "hi foo" (note: there should be two spaces between the words).请注意,这会将"hi 123 foo"变成"hi foo" (注意:单词之间应该有两个空格)。 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.这可能会在字符串末尾留下数字,这可能不是您想要的。

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

use this regex: regex='\s\d+'使用这个正则表达式:regex='\s\d+'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM