【问题标题】:Regular Expression for replace all non digit expect symbols替换所有非数字期望符号的正则表达式
【发布时间】:2020-11-24 09:22:43
【问题描述】:

我无法弄清楚这件事,我认为只有一种模式是可能的,请帮助我改进。

我有这个字符串2 / 3 items,但我不会只收到2 / 3

项目也可以用西里尔字母写,所以2 / 3 штуки

所以我认为最好的方法是使用\D all non digit (result 23)

但是这个删除也是我想保留的斜线,我该怎么办?

// this was my solution for now, 
// but it not complete for cirillic cause i have an error
// it return: 2 / 3 �
// maybe is something with encoding?
preg_replace('@[a-zA-Zа-яА-Я]*@', '', '2 / 3 штуки');

// so i chose to do this, but doesn't know how to keep slash
preg_replace('@[\D]*@', '', '2 / 3 штуки');
// it return: 23


# How to get 2 / 3 ?

【问题讨论】:

  • 可以排除斜线[^\d/]+
  • @Thefourthbird 很好,它工作!但正确的方法是[^\d\/]+,也适用于空格[^\d\s\/]+
  • 您使用@ 作为分隔符,因此您不必转义正斜杠。
  • @Thefourthbird 非常感谢你,我不知道这个
  • Артур,提取你需要的东西比替换要安全得多。

标签: php regex preg-replace multilingual


【解决方案1】:

你可以使用

if (preg_match('~\d+\s*/\s*\d+~u', $text, $match)) {
  echo $match[0];
}

另外,如果小数部分是可选的,请使用

preg_match('~\d+(?:\s*/\s*\d+)?~u', $text, $match)

如果您需要提取所有匹配项,请使用preg_match_all

preg_match_all('~\d+(?:\s*/\s*\d+)?~u', $text, $matches)

请参阅 regex demoPHP demo。请注意,preg_match 提取匹配项而不是删除它(就像 preg_replace 的情况一样)。

模式详情

  • \d+ - 一位或多位数字 - \s*/\s* - / 用零个或多个空格括起来
  • \d+ - 一位或多位数字

请注意,u 用于防止字符串中的空格不是常规 ASCII 空格,例如 \xA0

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 2011-02-03
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    相关资源
    最近更新 更多