2012-01-06 40 views
0

我想在PHP中使用preg_split将字符串拆分为术语。我需要提取普通单词(\ w),还需要提供货币(即使是货币符号)和数字术语(包括逗号和小数点)。任何人都可以帮助我,因为我似乎无法创建一个有效的正则表达式来使用preg_split来实现此目的。谢谢正则表达式在PHP中分割字母数字,货币和数字术语

+0

你能不能给你想要捕捉的东西的例子吗? – Biotox 2012-01-06 23:19:52

+0

我需要提取诸如: “1.545” “$ 143” “$ 13.43” “15亿” “你好” “G9” 感谢您的答复! – dscer 2012-01-06 23:26:30

+0

看起来你只是想捕捉出现的任何东西。你可以轻松地做一个dotall捕获。它只是'/.+/',或者它们是你需要过滤的字符串吗?我不明白你试图分裂的东西。 – Biotox 2012-01-06 23:31:18

回答

1

为什么不使用preg_match_all()而不是preg_split()

$str = '"1.545" "$143" "$13.43" "1.5b" "hello" "G9"' 
    . ' This is a test sentence, with some. 123. numbers' 
    . ' 456.78 and punctuation! signs.'; 

$digitsPattern = '\$?\d+(\.\d+)?'; 
$wordsPattern = '[[:alnum:]]+'; 

preg_match_all('/('.$digitsPattern.'|'.$wordsPattern.')/i', $str, $matches); 

print_r($matches[0]); 
+0

这与我所需要的非常接近。是否可以调整正则表达式来排除期限,除了在数字中间? 例如: “这是一个数字:43234.这些是一些词。” 你的解决方案导致: 阵列 ( [0] =>此 [1] =>是 [2] =>一个 [3] =>数 [4] => ** 43234 ** [5] =>这些 [6] => [7] =>一些 [8] => **字样** ) – dscer 2012-01-06 23:52:18

+0

我已经更新了我的答案。你能用新的正则表达式来测试吗? – 2012-01-06 23:59:12

+0

完美!谢谢! – dscer 2012-01-07 00:03:49

0

它解决您的问题分裂在空白? "/\s+/"

+0

不完全是,因为我除数字术语外,不想包含标点符号。 – dscer 2012-01-06 23:41:48

1

什么preg_match_all()这个[\S]+\b每个单词,然后你得到它的单词的数组。

大的棕色狐狸 - $ 20.25将返回

preg_match_all('/[\S]+\b/', $str, $matches); 

$matches = array(
[0] = 'Big', 
[1] = 'brown', 
[2] = 'fox', 
[3] = '$20.25' 
) 
+0

谢谢!这是完美的! – dscer 2012-01-07 00:04:19