Example:
$array = array('alpha beta','beta gamma','delta phi', '#alpha phi', 'beta phi');
$searchword = 'alpha';
$results = array_filter($array, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
print_r($results);
Array ( [0] => alpha beta [3] => #alpha phi )
I would like to find only the elements containing #alpha
, not alpha
.
The result I want is Array ( [3] => #alpha phi )
.
However, this doesn't work:
$array = array('alpha beta','beta gamma','delta phi', '#alpha phi', 'beta phi');
$searchword = '#alpha';
$results = array_filter($array, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
print_r($results);
Array ( )
I also tried $searchword = preg_quote('#alpha');
but that doesn't work either. I'm not familiar enough with regex to figure this out-- there must be some regex rule I'm missing out on?
Note: I am not looking to find all the hashtag keywords in the array. I want to search for a specific hashtag keyword.
Credit: I used one of the answers from here: Search for PHP array element containing string
PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array.
Remove the starting \b
preg_match("/$searchword\b/i", $var);
or
Use \B
preg_match("/\B$searchword\b/i", $var);
Why?
It's all about word boundaries \b
matches between word char and a non-word char or vice-versa. Since the first character is #
which is a non-word character and before that character there exists the start of the line boundary. \B
is the suitable one for this, which matches between two non-word chars or two word chars. Here start of the line , #
so there must exists \B
in-between not \b
.
Or you can also use strpos
instead of preg_match
as
$searchword = '#alpha';
$results = array_filter($array, function($var) use ($searchword) { return (strpos($var,$searchword)>-1); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With