PHP中的字符串操作

时间:2018-09-11 09:31:16

标签: php regex

我有一个功能:

function Validate($name)
{
    $rename = 'Rename' .$name;
    if (strlen($rename) > 50) {
        $rename = substr($rename, 0, 48) . '..';
    }
    return $rename;
}

该函数的调用方式如下:

$data['name'] = Validate($duplicate->name."_").$i++;

如果名称为50个字符,则将其缩短为48个字符,并在末尾加..如果名称是50个以.._ somedigits结尾的字符。 我想做$ rename = substr($ rename,0,45)。 '..'。$后缀;我想用sffix进行此额外检查 任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

您可以使用正则表达式^.*_0$

如果此正则表达式匹配,则可以将子字符串设置为45个字符。 Reg

答案 1 :(得分:0)

$strings = [
    'abcdefghijklmnopqrstuvwxyz',
    'abcdefghijklmnopqrstuvwxyz_12',
    'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx',
    'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz',
    'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz_12',
];
foreach($strings as $str) {
    if (preg_match('/_\d+$/', $str)) {
        echo preg_replace('/^(?=.{51}).{45}\K.+(_\d+)$/', '..$1', $str),"\n";
    } else {
        echo preg_replace('/^(?=.{51}).{48}\K.+$/', '..', $str),"\n";
    }
}

输出:

abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz_12
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv..
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs.._12

第一个正则表达式解释:

^               : beginning of string
    (?=.{51})   : lookahead, 0-length assertion that makes sure we have, at least, 51 characters
    .{45}       : exactly 45 characters
    \K          : forget all we have seen until this position
    .+          : 1 or more any character
    (_\d+)      : group 1, underscore and last digits
$               : end of line

第二个正则表达式说明:

^               : beginning of string
    (?=.{51})   : lookahead, 0-length assertion that makes sure we have, at least, 51 characters
    .{48}       : exactly 48 characters
    \K          : forget all we have seen until this position
    .+          : 1 or more any character
$               : end of line

答案 2 :(得分:0)

您要串联$rename = 'Rename' .$name;,然后根据该$rename得到strlen。这样就可以在字符串的长度上添加“重命名”。

如果您打算这样做,可以使用正则表达式_\d+$来检查字符串是否以,下划线和一个或多个数字结尾。

function Validate($name)
{
    $suffix = "suffix";
    $rename = 'Rename' . $name;
    $re = '/_\d+$/';
    if (strlen($rename) > 50) {
        if (preg_match($re, $rename)) {
            return substr($rename, 0, 45) . '..' . $suffix;
        }
        return substr($rename, 0, 48) . '..';

    }
    return $rename;
}

Demo