在括号正则表达式中匹配x个单词

时间:2010-11-16 17:41:21

标签: php preg-replace

如果它包含4个或更多单词,我试图从字符串中删除括号。我一直在挠头,无法随身携带。

preg_replace('#\([word]{4,}\)#', '', $str); # pseudo code

示例字符串:

  

Robert Alner基金标准公开NH平坦赛(由Andrew Stewart慈善基金会支持)

要匹配(括号中超过x个单词)并删除:

  

(由Andrew Stewart慈善基金会支持)

我有两个数据来源,我正在使用:

similar_text($str1, $str2, &$percent)

比较和括号中的longish字符串对于一个来源是唯一的。

4 个答案:

答案 0 :(得分:0)

您不需要preg_replace()。只需使用substr_count()计算空格,然后使用str_replace()

答案 1 :(得分:0)

语法[…]具有特殊含义。 […]被称为character classes,并且与列出的字符之一匹配。因此,[word]会匹配word中的一个字符。

现在,如果你想匹配单词,你应该首先定义一个单词是什么。如果一个单词是一个字符序列,除了空白字符(\S代表所有非空白字符),你可以这样做:

/\S+(\s+\S+){3,}/

这匹配由空格字符(\s)分隔的四个或更多单词(非空白字符序列)的任何序列。

括号中有四个或更多单词:

/\(\S+(\s+\S+){3,})/

请注意,\S除了空白字符外,其他任何内容都匹配,即使是周围的括号也是如此。因此,您可能希望将\S更改为[^\s)]

/\([^\s)]+(\s+[^\s)]+){3,})/

答案 2 :(得分:0)

我不是专家,但这可能有用。 这是一个模式字符串:

/\(((\w*?\s){3,}[\w]+?.*?)\)/i

这里是PHP中的替换字符串,用于除前导和尾随转义括号外的所有内容。

$1

这是preg_replace函数。

preg_replace('/\(((\w*?\s){3,}[\w]+?.*?)\)/i',$1,$string);

答案 3 :(得分:0)

嗯,你很亲密......

preg_replace('#\((\b\w+\b[^\w)]*){4,}\)#', '', $str);

基本上,内部子模式(\b\w+\b[^\w)]*)匹配一个词边界(意思是不在两个单词字符之间),后跟至少一个单词字符(a-z0-9),然后是另一个单词 - 边界,最后是0个或更多字符,这些字符不是单词字符,不是) ...

测试:

$tests = array(
    'test1 (this is three)',
    'test2 (this is four words)',
    'test3 (this is four words) and (this is three)',
    'test4 (this is five words inside)',
);

foreach ($tests as $str) {
    echo $str . " - " . preg_replace('#\((\b\w+\b[^\w)]*){4,}\)#', '', $str) . "\n";
}

给出:

test1 (this is three) - test1 (this is three)
test2 (this is four words) - test2
test3 (this is four words) and (this is three) - test3  and (this is three)
test4 (this is five words inside) - test4
相关问题