简体   繁体   English

正则表达式模式只匹配不包含空格PHP的字符串

[英]regex pattern to match only strings that don't contain spaces PHP

I want to match the word/pattern that is contained in the variable, but only match against the words that don't have white spaces. 我想匹配变量中包含的单词/模式,但只匹配没有空格的单词。 Please give suggestions. 请给出建议。

$var = 'look'; $ var ='look';

$array = ('look', 'greatlook', 'lookgreat', 'look great', 'badlook', 'look bad', 'look ', ' look'); $ array =('look','greatlook','lookgreat','look great','badlook','look bad','look','look');

matches words: look, greatlook, lookgreat, badlook 匹配单词:look,greatlook,lookgreat,badlook

non matches: look great, bad look, look (trailing space(s)), (space(s)) look. 不匹配:看起来很棒,看起来很糟糕,看起来(尾随空间),(空间)看起来。

The syntax of the below functions are OK, but it matches everything 以下函数的语法没问题,但它匹配所有内容

$match = preg_grep ("/$var/", $array); $ match = preg_grep(“/ $ var /”,$ array);

$match = preg_grep ("/^$var/", $array); $ match = preg_grep(“/ ^ $ var /”,$ array); (match words with 'look' at the start) (在开头匹配'look'字样)

but when I include the [^\\s], it gives an error 但是当我包含[^ \\ s]时,它会出错

$match = preg_grep ("/$var[^\\s]/", $array); $ match = preg_grep(“/ $ var [^ \\ s] /”,$ array);

Parse error: syntax error, unexpected '^', expecting T_STRING or T_VARIABLE 解析错误:语法错误,意外'^',期待T_STRING或T_VARIABLE

TIA TIA

The regex would be ^(?=.*look)[^\\s]+$ 正则表达式将是^(?=.*look)[^\\s]+$

preg_match("/^(?=.*{$var})[^\\s]+$/", $str);

<?
  $str = array('look', 'greatlook', 'lookgreat', 'look great', 'badlook', 'look bad', 'look ', ' look');
  $var = "look";
  $matches = preg_grep("/^(?=.*{$var})[^\\s]+$/", $str);
  print_r ($matches);
?>
//output
Array
(
    [0] => look
    [1] => greatlook
    [2] => lookgreat
    [4] => badlook
)

采用:

$match = preg_grep("/^\S*$var\S*$/", $array);
$match = preg_grep ("/{$var}[^\s]/", $array);

我相信你需要将变量括在花括号中,因为字符在没有空格的情况下继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM