Jump to content

[SOLVED] regular expression- preg_grep


meltingpoint

Recommended Posts

I am searching an array for instances of words or partial words.  I need to have the regular expression check to make sure that there is a -space- at the beginning.  This way- it will not count matches of the string in the middle of words.

 

here is what I have tried;

$search_var = "sil";

$match = preg_grep("/$search_var/i", $my_array);
//this was the original that led me to have to check for the space at the beginning.
//
//so I tried;
$match = preg_grep("/^([:space:])$search_var/i", $my_array);//DID NOT WORK

I know I am making a stupid error- but for the life of me- I cannot figure it out.

:facewall:

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/170440-solved-regular-expression-preg_grep/
Share on other sites

more accurately, \b is a word boundary and will match anything not considered a "word" character, as defined by \w.  \w being defined as a-z A-Z 0-9 _ and any other characters considered to be word characters defined by local settings. So basically, \b$search_var  will match if there is a space before, it, but it will also match if there is any other non-alphanumerical character before it. 

 

Also, \b only matches at where you put it.  \b$search_var  does not match at the beginning and end of $search_var;  it just looks for a non-word character at the beginning.  If you want it to match at the beginning and end, you would do \b$search_var\b just like anything else. 

 

Using \s is preferred, however, note that \s is shorthand for "whitespace" characters, not just a space made from the spacebar. It will also match tabs and newline characters.  If you want to only match a space and nothing else, you would use a physical space in your regex:

 

$match = preg_grep("/ $search_var/i", $my_array);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.