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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.