duanjing4623 2015-09-15 20:24
浏览 47
已采纳

修剪Wordpress帖子标题

Following PHP code shows WordPress media files at user front end

<?php 
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'author' => $current_user->ID,
'post_parent' => $post->ID,
'caller_get_posts'=> 1,
);
$attachments = get_posts( $args );
if ($attachments) {
foreach ($attachments as $attachment) {
echo '<tr><td><a href="'.wp_get_attachment_url($attachment->ID).'" rel="shadowbox" title="'.$attachment->post_excerpt.'">';
echo $attachment->_wp_attached_file;
echo '</a>      
</td>
}
}?>

Above code shows the complete file name at front end. If someone upload sssssssssssssssssssssssssssssssssssssssssssss.txt, 123457xxxxxxxxxxxxxxx.gif or xls, pdf, docx and all other extensions with different long file names it create mess on my theme. Can anyone please help guide me how to trim the file name and show something like sssssss...ssss.txt xxxxxx...xxxx.pdf or gif at front end?

I tried following function for specific file in functions.php still no change

$wp_attached_file = 'sssssssssssssssssssssssssssssssssssssssssssss.txt';
echo preg_replace('/(.{3}).*(\..{2,4})/', '$1...$2', $wp_attached_file);

and

$attachment = $wp_attached_file;
echo preg_replace('/(.{3}).*(\..{2,4})/', '$1...$2', $wp_attached_file);

It is working now, I replace following line

echo ($attachment->_wp_attached_file);

with

echo preg_replace('/(.{15}).*(.{5})(\..{2,4})/', '$1...$2$3', $attachment->_wp_attached_file);
  • 写回答

1条回答 默认 最新

  • doudiewen9435 2015-09-16 04:56
    关注

    You could use a regex like

    /(.{3}).*(\..{2,4})/
    

    This captures the first three characters, (.{3}).
    Then ignores everything, .*
    Until the last period and the next 2-4 characters (for ai, mpeg, jpg could filter that to 3 if it will always be 3), \..{2,4}. The .{2,4} bit being any character 2-4 strings long.

    PHP Usage:

    $wp_attached_file = 'sssssssssssssssssssssssssssssssssssssssssssss.txt';
    echo preg_replace('/(.{3}).*(\..{2,4})/', '$1...$2', $wp_attached_file);
    

    Output:

    sss....txt
    

    Regex101 Demo: https://regex101.com/r/aR1vJ2/2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?