Use PHP functions in JavaScript

JavaScript preg_grep

Searches array and returns entries which match regex

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
function preg_grep (pattern, input, flags) {
    // Searches array and returns entries which match regex  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/preg_grep    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: If pass pattern as string, must escape backslashes, even for single quotes
    // %          note 2: The regular expression itself must be expressed JavaScript style
    // %          note 3: It is not recommended to submit the pattern as a string, as we may implement
    // %          note 3:   parsing of PHP-style expressions (flags, etc.) in the future    // *     example 1: var arr = [1, 4, 4.5, 3, 'a', 4.4];
    // *     example 1: preg_grep("/^(\\d+)?\\.\\d+$/", arr);
    // *     returns 1: {2: 4.5, 5: 4.4}
    var p = '',
        retObj = {};    var invert = (flags === 1 || flags === 'PREG_GREP_INVERT'); // Todo: put flags as number and do bitwise checks (at least if other flags allowable); see pathinfo()
 
    if (typeof pattern === 'string') {
        pattern = eval(pattern);
    } 
    if (invert) {
        for (p in input) {
            if (input[p].search(pattern) === -1) {
                retObj[p] = input[p];            }
        }
    } else {
        for (p in input) {
            if (input[p].search(pattern) !== -1) {                retObj[p] = input[p];
            }
        }
    }
     return retObj;
}
external links: original PHP docs | raw js source

Examples

Running

1
2
var arr = [1, 4, 4.5, 3, 'a', 4.4];
preg_grep("/^(\\d+)?\\.\\d+$/", arr);

Should return

1
{2: 4.5, 5: 4.4}

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have preg_grep goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

No comments yet. Be the first!


Contribute a New function

More functions

In this category

» preg_grep
preg_quote
sql_regcase

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !