php - 如何在 php 和 javascript 中使用正则表达式检测空格分隔的单词(在全文搜索查询中)

标签 php javascript regex

我需要检测文本中以空格分隔的单词。例如我的文字是:

some parent +kid -control "human right" world

现在我需要检测someparentworld。 (所有前后没有 + - ( ) < > 的词,以及引号内的所有词都必须丢弃)所以我用 preg_match_all() 编写这个正则表达式:

(?:^|[\s]+)((?:(?![\+\(\)\<\>\s\-\"]).)+)(?:[\s]+|$)

但它只检测一些世界。我该如何解决?

编辑

Javascript 我也需要它。但它似乎不适用于 Javascript。我怎样才能用 javascript 做到这一点?

编辑

我找到了一个解决方案,但它似乎很愚蠢。你有什么想法?

$str = 'some parent +kid -control "my human right" world';
$words=array();
$quot=false;
$discard=false;
$word='';
for($i=0;$i<=strlen($str);$i++){
    $chr=substr($str,$i,1);
    if($chr=='"'){
        if($quot){
            $quot=false;
        }else{
            $quot=true;
        }
        continue;
    }
    if($quot)continue;
    if($chr==' '||$i==strlen($str)){
        if(strlen($word)&&!$discard)$words[]=$word;
        $discard=false;
        $word='';
        continue;
    }elseif(in_array($chr,array('+','-','(',')','<','>'))){
        $discard=true;
        continue;
    }
    $word.=$chr;
}
print_r($words);//Array ( [0] => some [1] => parent [2] => world ) 

编辑 PHP的最终方式(这是针对多语言查询)(特别感谢橡胶靴):

$query='some parent +kid -control "my human right" world';
$result=array();
if(preg_match_all('/(?:"[^"]+")|(?:^|[\s])(?P<q>(?:(?![\+\(\)\<\>\s\-\"]).)+)/',$query,$match)){
    $result=array_filter($match['q'],'strlen');
}
print_r($result);// some,parent,world

javascript的最终方式(多语言查询)(特别感谢rubber boots):

var query='some parent +kid -control "my human right" world';
var result=Array();
var tmp;
var patt=RegExp('(?:"[^"]+")|(?:(?:^|\\s)((?:(?![\\+\\(\\)\\<\\>\\s\\-\\"]).)+))', 'g');
while(tmp = patt.exec(query)){
    if(typeof(tmp[1])!=='undefined') result.push(tmp[1]);
}
alert(result);// some,parent,world

最佳答案

如果给出以下字符串:

 $t ='some parent +kid -control "human huhu right" world';

也可以使用相当简单的表达式根据您的规范提取单词:

 $r = '/ (?:" [^"]+ ")? \s?
         (?<!\S) \b (\w+)
       /x';
 preg_match_all($r, $t, $matches);

这导致:

foreach($matches[1] as $m) echo $m . "\n";

some
parent
world

使用的技术:

expr (?:"[^"]+ ")? 使用引号及其内容。


附录:Javascript

对于 Javascript,您需要使用稍微复杂的方法,Javascript 没有lookbehind assertions,我们伪造它们 (?:^|\\s) 在允许的词前面。

这将起作用:

  var t = 'some parent +kid -control "human huhu right" world';
  var r = /(?:"[^"]+")?(?:^|\s)(\b\w+)/g;
  var a = [];
  while(m = r.exec(t)) a.push(m[1]);

我们在这里使用相同的技术 - 在 $1 中为我们需要的词生成捕获的子匹配。

数组 a 的内容,(document.getElementById("myhtml").innerHTML = a;) 将包含:

some,parent,world

关于php - 如何在 php 和 javascript 中使用正则表达式检测空格分隔的单词(在全文搜索查询中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721251/

相关文章:

php - SQL 查询选择行数,即使变量列表中的列中至少有一个值匹配

php - laravel:mailgun 发送双封邮件

javascript - Bootstrap Accordion 不工作。

JavaScript 正则表达式 : accept only space and letters from all languages

regex - 帮助正则表达式包含和排除

php - JavaScript 中的 RegExp 在 PHP 中抛出错误

php - Codeigniter 多对多错误

php - 使用 Wordpress 建立数据库连接时出错

javascript - 不包括零的最小数量

javascript - 谷歌地图 V3 : Updating Markers Periodically