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

时间:2016-03-06 06:25:06

标签: php regex

我有以下示例字符串

  

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

我想要以下结果

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

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

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

我知道它并不多,但我一直在访问许多网站来学习RegEx,但我仍然试图了解这种语言。如果您的答案可以请包含评论,那么我可以将其分解并从中学习,以便最终我可以开始进一步修改它。

4 个答案:

答案 0 :(得分:2)

使用preg_match_all

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

Regex101 Demo

说明:

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

  • |

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

答案 1 :(得分:1)

为了提供另一种选择,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);
?>

请参阅a demo on ideone.comregex101.com

答案 2 :(得分:0)

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

代码:(Demo

$txt = 'Lot99. Is it 1+3 or 5 or 6.53';
var_export(
    preg_split('~(?:\d+\.\d+|\w+|\S)\K *~', $txt, null, 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.单个非空白字符然后忘记匹配的字符,然后占用零个或多个空格。空格是拆分时唯一被丢弃的字符。

答案 3 :(得分:0)

在 PHP 中使用 for

示例-

$value=array("Lot99",".","Is","it","1","+","3","or","5","or","6.53");
for ($i = 0; $i < count($value); $i++) {
    echo $value[$i]." ";
}