Sanitization of User-Supplied Regular Expressions in PHP

前端 未结 5 860
盖世英雄少女心
盖世英雄少女心 2020-12-20 21:03

I want to create a website where users can test regular expressions (there are many out there already...such as this one: http://www.pagecolumn.com/tool/pregtest.htm). Basic

5条回答
  •  死守一世寂寞
    2020-12-20 21:51

    I think PHP itself will check the regex. Here's a sample script I made :

    // check for input, and set max size of input
    if(@!empty($_POST['regex'])
        && @!empty($_POST['text'])
        && strlen($_POST['regex'])<1000
        && strlen($_POST['text'])<2000
        ){
        // set script timeout in case something goes wrong (SAFE MODE must be OFF)
        $old_time=ini_get('max_execution_time');
        if(!set_time_limit(1)) die('SAFE MODE MUST BE OFF'); // 1 sec is more then enough
    
        // trim input, it's up to you to do more checks
        $regex=trim($_POST['regex']);
        // don't trim the text, it can be needed
        $input=$_POST['text'];
        // escape slashes
        $regex=preg_replace('/([\\/]+)?//', '\/', $regex);
    
        // go for the regex
        if(false===$matched=@preg_match('/'.$regex.'/', $input, $matches)){
                // regex was tested, show results
                echo 'Matches: '.$matched.'
    '; if($matched>0){ echo 'matches:
    '; foreach($matches as $i => $match){ echo $i.' = '.$match.'
    '; } } } // set back original execution time set_time_limit($old_time); }

    Anyways, NEVER EVER use eval() with user submitted strings.

    Additionally, you can do some simple minimalistic sanitizing, but that's up to you. ;)

提交回复
热议问题