meltingpoint Posted August 15, 2009 Share Posted August 15, 2009 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. Quote Link to comment Share on other sites More sharing options...
oni-kun Posted August 15, 2009 Share Posted August 15, 2009 If you're wanting to match a space before search term.. $match = preg_grep("/^\s$search_var/i", $my_array); Quote Link to comment Share on other sites More sharing options...
meltingpoint Posted August 15, 2009 Author Share Posted August 15, 2009 Thanks for that. I was also experimenting and found that using b\ works too. Example; $match = preg_grep("/\b$search_var/i", $my_array); this makes sure that the search string is at the beginning of the word Cheers Quote Link to comment Share on other sites More sharing options...
oni-kun Posted August 15, 2009 Share Posted August 15, 2009 \b is the word boundry or matches white space at the beginning or end of a match, \s matching white space before just the term, which you should use if you were to match multiple spaces in some case... No problem. Quote Link to comment Share on other sites More sharing options...
.josh Posted August 16, 2009 Share Posted August 16, 2009 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); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.