Good alternative to eregi() in PHP

前端 未结 8 1578
感情败类
感情败类 2021-01-04 08:39

I often find myself doing quick checks like this:

if (!eregi(\'.php\', $fileName)) {
    $filename .= \'.php\';
}

But as eregi() was deprec

相关标签:
8条回答
  • 2021-01-04 08:53

    stristr achieves exactly the same result as eregi (at least when you don't use regular expressions):

    if (!stristr($fileName, '.php'))
        $filename.='.php';
    

    You could also make a "fake" eregi this way:

    if (!function_exists('eregi')) {
        function eregi($find, $str) {
            return stristr($str, $find);
        }
    }
    

    Update: Note that stristr doesn't accept regular expressions as eregi does, and for this specific case (checking the extension), you'd better go with vartec's solution.

    0 讨论(0)
  • 2021-01-04 08:55

    I generally create and endsWith function; or other simple string manipulation functions for this kind of stuff.

    function endsWith($string, $end){
        return substr($string, -strlen($end)) == $end;
    }
    
    0 讨论(0)
  • 2021-01-04 09:00

    Try this, I'm using this quite a lot since I updated to PHP 5 recently.

    Previously:

    if(eregi('-', $_GET['id'])
    {
       return true;
    }
    

    Now I'm using this - it works just as good.

    if(preg_match('/(.+)-(.+)/', $_GET['id'])) {
    {
       return true;
    }
    

    Just replace your code with the following, and you shouldn't have any hitch of difference within your code. If you're wondering why PHP remove eregi() it's because of the performance issues it has when used a lot, so it's better to use preg_match() as it's more specific in searching so it has better performance and rendering times.

    Let me know how this works for you.

    0 讨论(0)
  • 2021-01-04 09:03

    Of course you are aware, that this doesn't do what you expect it do do? In regexp '.' means any character, so eregi('.php',$fileName) means filename with any character followed by 'php'. Thus for example "blabla2PHP.txt" will match your regexp.

    Now what you want to do is this:

    $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
    if(strtolower($file_ext) != 'php') 
       $filename .= '.php';
    
    0 讨论(0)
  • 2021-01-04 09:06

    Good alternative for eregi() is preg_match() with i modifier:

    if (! preg_match('/.php/i',$fileName))
          $filename.='.php';
    
    0 讨论(0)
  • 2021-01-04 09:07

    Perhaps you should consider refactoring your code to do this instead:

    if (substr($fileName, -4, 4) !== '.php')
        $fileName .= '.php';
    

    As stated in other answers to this question, eregi('.php') will search for anything followed by 'php' ANYWERE in the file (not just at the end).

    0 讨论(0)
提交回复
热议问题