使用preg_match获取文件名

时间:2010-06-25 15:28:14

标签: php regex preg-match

我们在新闻帖子中使用自定义bbcode

[newsImage] imageName.jpg [/ newsImage]

我想使用preg_match从这些标签之间获取imageName.jpg。整个帖子存储在一个名为$ newsPost的变量中。

我是regex的新手,我无法弄清楚在preg_match中使用正确的表达式来获得我想要的东西。

感谢任何帮助。另外,你们中的任何人都知道学习正则表达式中每个角色的好资源吗?

4 个答案:

答案 0 :(得分:2)

preg_match_all('/\[newsImage\]([^\[]+)\[\/newsImage\]/i', $newsPost, $images);

变量$images应该包含您的匹配列表。

http://www.php.net/manual/en/regexp.introduction.php

答案 1 :(得分:1)

回答你的第二个问题:一个非常好的正则表达式教程是regular-expressions.info

除此之外,它还包含regular expression syntax reference

由于不同的正则表达式使用不同的语法,因此您还需要查看regex flavor comparison page

答案 2 :(得分:1)

正如罗布所说,但最后逃避了]

preg_match('/\[newsImage\]([^\[]+)\[newsImage\]/i', $newsPost, $images);

$ images [1]将包含图像文件的名称。

答案 3 :(得分:0)

这不是您要求的,但您可以使用以下代码将[newsImage]标签替换为标签,但它并不完美,因为如果您有空标签,它会掉下来[newsImage] [/ newsImage]

function process_image_code($text) {
        //regex looks for [newsImage]sometext[/newsImage]
        $urlReg ="/((?:\[newsImage]{1}){1}.{1,}?(?:\[\/newsImage]){1})/i";
        $pregResults = preg_split ($urlReg , $text, -1, PREG_SPLIT_DELIM_CAPTURE);
        $output = "";

        //loop array to build the output string
        for($i = 0; $i < sizeof($pregResults); $i++) {

            //if the array item has a regex match process the result
            if(preg_match($urlReg, $pregResults[$i]) ) {
                $pregResults[$i] = preg_replace ("/(?:\[\/newsImage]){1}/i","\" alt=\"Image\" border=\"0\" />",$pregResults[$i] ,1);

                // find if it has a http:// at the start of the image url
                if(preg_match("/(?:\[newsImage]http:\/\/?){1}/i",$pregResults[$i])) {
                    $pregResults[$i] = preg_replace ("/(?:\[newsImage]?){1}/i","<img src=\"",$pregResults[$i] ,1);
                }else {
                    $pregResults[$i] = preg_replace ("/(?:\[newsImage]?){1}/i","<img src=\"http://",$pregResults[$i] ,1);
                }

                $output .= $pregResults[$i];
            }else {
                $output .= $pregResults[$i];
            }
        }

        return $output;
    }