In PHP, what is a fast way to search an array for values which contain a substring? In PHP, what is a fast way to search an array for values which contain a substring? ajax ajax

In PHP, what is a fast way to search an array for values which contain a substring?


Use preg_grep():

$matches = preg_grep('/al/', $streetNames);

Note: this method like yours will be a brute force search. If you're searching a huge list of names (hundreds of thousands) or searching a huge number of times then you may need something better. For small data sets this is fine however.


The only way to get faster than looking through all the strings would be to have a data structure optimized for this kind of thing, a trie. You may not have control over what the webservice gives you, but if you can cache the result on your server and reuse it for serving many requests, then building a trie and using that would be much faster.


I think what you're looking for is preg_grep()

You can search either for elements starting with the input text:

$result = preg_grep('/^$input/', $streetNames);

or for elements that contain the text in any place:

$result = preg_grep('/$input/', $streetNames);

or you can also anchor the search to the end but that doesn't look so useful