【问题标题】:Populating Database from Directory从目录填充数据库
【发布时间】:2011-03-24 20:03:26
【问题描述】:

我想扫描一个包含图像文件的目录并用它们填充我的数据库。图像具有常规且受控的名称,例如 top_1、top_200、bottom_3。我需要与“_”之前的单词匹配的正则表达式的帮助,因为它们中的每一个在数据库中都有不同的关系。

我现在可以扫描目录:

function scan_img_dir()
    {

            $dir = '/images/';  
            $scan = scandir($dir);  

            for ($i=0; $i<count($scan); $i++) 
            {  
                //Being Pseudocode
                $stringBeforeUnderscore = Some_String_Manipulation($scan[$i]);
                switch($stringBeforeUnderscore)
                {
                    case 'top':
                        insert into db with the top relationship
                        break;
                    case 'bottom':
                        insert into db with the bottom relationship
                        break;
                }
            }  


    }

在“_”之前提取字符串的代码的任何帮助都会很棒。任何改进逻辑或代码的帮助都将是锦上添花!提前致谢。

【问题讨论】:

  • 这非常有效。谢谢你。我最终选择了接受的答案,因为它更简单并且不会爆炸成数组。

标签: php codeigniter


【解决方案1】:
$stringBeforeUnderscore = substr($scan[$i], 0, strpos($scan[$i], '_'));

【讨论】:

  • 比爆炸还容易。谢谢。
【解决方案2】:
$str = 'asd_asdad_aef';

preg_match_all('/([^_]*)/', $str, $matches);

$stringBeforeUnderscore = $matches[0][0];

【讨论】:

  • 感谢您的回复。我最终使用了explode,结果发现我不需要正则表达式的复杂性。感谢你的回答。投票赞成。
  • 谢谢。是的,explode 效率更高。
猜你喜欢
  • 2019-03-03
  • 2012-11-04
  • 1970-01-01
  • 2010-09-26
  • 2012-06-25
  • 2011-07-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多