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

Posted by Jamex on Stack Overflow See other posts from Stack Overflow or by Jamex
Published on 2010-06-03T04:05:25Z Indexed on 2010/06/03 4:14 UTC
Read the original article Hit count: 257

Filed under:
|

Hi,

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

© Stack Overflow or respective owner

Related posts about php

Related posts about regex