正则表达式用于在 php 中分隔单词数字和符号


Regex to separate words numbers and symbols in php

>我有以下示例字符串

Lot99.是 1+3 还是 5 还是 6.53

我想要以下结果

["Lot99",".","Is","it","1","+","3","or","5","or","6.53"]

因此,结果消除了空格,将单词分开,但如果单词和数字之间没有空格,则将它们放在一起,如果不在单词的开头或结尾,则分隔数字。分隔符号,如 +-.,!@#$%^&*();'/|<> 但如果 2 个数字之间的小数点,例如 2.2 应保留为 2.2,则不分隔

符号

到目前为止,我有这个正则表达式/s+[a-zA-Z]+|'b(?='W)/

我知道它不多,但我一直在访问许多网站来学习正则表达式,但我仍在努力了解这种语言。如果您的答案可以包括评论,以便我可以分解并从中学习,以便我最终可以开始进一步修改它。

使用 preg_match_all

preg_match_all('~(?:'d+(?:'.'d+)?|'w)+|[^'s'w]~', $str, $matches);

正则表达式 101 演示

解释:

  • (?:'d+(?:'.'d+)?|'w)+会匹配数字(浮点数或整数)或单词字符一次或多次,从而匹配foo99.988gg等字符串

  • |

  • [^'s'w]匹配非单词、非空格字符。

为了提供另一种选择,PHP提供了美妙的(*SKIP)(*FAIL)结构。它说的是以下内容:

dont_match_this|forget_about_this|(but_keep_this)

将其分解为您的实际问题,这将是:

        (?:'d+'.'d+)    # looks for digits with a point (float)
        (*SKIP)(*FAIL)  # all of the left alternatives should fail
        |               # OR
        ([.'s+]+)       # a point, whitespace or plus sign 
                        # this should match and be captured
                        # for PREG_SPLIT_DELIM_CAPTURE

PHP中,这将是:

<?php
$string = "Lot99. Is it 1+3 or 5 or 6.53";
$regex = '~
            (?:'d+'.'d+)    # looks for digits with a point (float)
            (*SKIP)(*FAIL)  # all of the left alternatives should fail
            |               # OR
            ([.'s+]+)       # a point, whitespace or plus sign 
                            # this should match and be captured
                            # for PREG_SPLIT_DELIM_CAPTURE
          ~x';              # verbose modifier
$parts = preg_split($regex, $string, 0, PREG_SPLIT_DELIM_CAPTURE);
print_r($parts);
?>

观看有关 ideone.com 和 regex101.com 的演示。

@Jan肯定是在使用理想的函数preg_split()。 我将提供一种不需要使用 (*SKIP)(*FAIL) 或捕获组的替代模式。

代码:(演示)

$txt = 'Lot99. Is it 1+3 or 5 or 6.53';
var_export(
    preg_split('~(?:'d+'.'d+|'w+|'S)'K *~', $txt, 0, PREG_SPLIT_NO_EMPTY)
);

输出:

array (
  0 => 'Lot99',
  1 => '.',
  2 => 'Is',
  3 => 'it',
  4 => '1',
  5 => '+',
  6 => '3',
  7 => 'or',
  8 => '5',
  9 => 'or',
  10 => '6.53',
)

实际上,该模式表示匹配 1。 单个浮点值 2. 一个或多个连续的数字/字母/下划线或 3. 单个非空格字符然后忘记匹配的字符,然后消耗零个或多个空格。 空格是拆分时唯一丢弃的字符。