简体   繁体   中英

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';

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

matches words: 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 words with 'look' at the start)

but when I include the [^\\s], it gives an error

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

Parse error: syntax error, unexpected '^', expecting T_STRING or T_VARIABLE

TIA

The regex would be ^(?=.*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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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