0

我正在尝试使用 preg_split 将字符串拆分为 PHP 中的术语。我需要提取普通单词( \w )以及货币(甚至货币符号)和数字项(包括逗号和小数点)。谁能帮帮我,因为我似乎无法创建一个有效的正则表达式来用于 preg_split 来实现这一点。谢谢

4

3 回答 3

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]); 
于 2012-01-06T23:41:28.260 回答
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'
)
于 2012-01-06T23:47:03.107 回答
0

它是否解决了您在空格上拆分的问题?"/\s+/"

于 2012-01-06T23:39:54.423 回答