错误类型 - 2:preg_replace()[function.preg-replace]:编译失败:缺少)

时间:2011-11-15 09:16:50

标签: php preg-replace

我有以下错误:

错误类型 - 2:preg_replace()[function.preg-replace]:编译失败:丢失)偏移量为25:位于第766行的/var/www/hosting/com/galerielaboratorio/scripts/functions.php

这是功能:

function getThumbName($photo, $name = 'thumb') {

$ext = preg_replace ("/.*\./", "", $photo);
$photo = preg_replace ("/\.". $ext ."$/", "" , $photo). "." . $name . "." .$ext; // this line causes the error  

return $photo;

}

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

无法阅读您的表达,但您遗漏了一个)() - 对定义表达式组。一个(没有相应的)只是无效(这就是错误消息试图告诉你的内容)。如果您想要文字(,则必须将其\(

转义

但是,请查看pathinfo()explode()str_replace()。这不是正则表达式的场景

$ext = pathinfo($photo, PATHINFO_EXTENSION);
$photo = basename($photo) . '.' . $name . '.' . $ext;

答案 1 :(得分:0)

不知道哪里出错了;从代码中可以看出,因为你正在构建一个动态的正则表达式。无论如何,这里有一个供您欣赏的选择,它包含的错误检查比原始功能稍多。

<?php
function getThumbName($photo, $name = 'thumb') {
    if( $ext = getExtension( $photo ) ) {
        return basename( $photo, $ext ) . 'thumb.' . $ext;
    }
    return false;
}

/**
 * Returns the file extension if it exists, false otherwise.
 * @param string $filename
 * @return string|bool
 */
function getExtension( $filename ) {
    return pathinfo( $filename, PATHINFO_EXTENSION );
}

echo getThumbName( 'foo.jpg' ) . PHP_EOL; // foo.thumb.jpg
echo getThumbName( 'slightly.more.complex.gif' ) . PHP_EOL; // slightly.more.complex.thumb.gif

echo getThumbname( 'This is where it gets interesting' ) . PHP_EOL; // false.
相关问题