【问题标题】:substr PHP shorten lengh of a string (WordPress Plugin)substr PHP缩短字符串的长度(WordPress插件)
【发布时间】:2015-06-07 06:27:27
【问题描述】:

我是 PHP 的新手,我只是在学习。但是我遇到了一个我真正遇到的问题。

我正在使用插件在 WordPress 中工作,我正在尝试缩短该插件中的字符串,以便它只显示少量文本而不是大段。

我从阅读这个网站和包括 PHP.net 在内的其他网站知道我需要使用 'substr' 主要问题是我认为我需要添加的不仅仅是字符串。

在我的工作中,没有缩短 ['post_content'] 中的字符串有一些东西我不确定它如何与 PHP 的语法一起使用。

这是我使用我找到的资源想出的。在末尾添加 ... 也很棒。

<?php

if (strlen($property) > 15) // if you want...
{
    $maxLength = 14;
    $property = substr($property, 0, $maxLength);
}
?>

这是有效的,但没有缩短

<?php echo $property['post_content']; ?> 

资源

Get first n characters of a string

Shorten a text string in PHP

Shorten string with a "..." body

http://php.net/manual/en/function.substr.php

【问题讨论】:

  • 对我来说不清楚你在问什么。也许你可以让你的问题更清楚。但是,您可能还想看看 mb_substr()。

标签: php string wordpress substr


【解决方案1】:

试试这个

$property = (strlen($property) > 15) ? substr($property,0,14): $property ; 

【讨论】:

    【解决方案2】:
    <?php
    if (strlen($property['post_content']) > 15) // if you want...
    {
       $mystring= substr($property['post_content'], 0,14);
    }
    echo $mystring; 
    ?>
    

    【讨论】:

    • user1374650 和 Kamran Adil 感谢您的回复,我错过了回声,我是多么愚蠢……另外,如果它不是很麻烦,我将如何添加它,这样它就不会拆分文本中间的句子。
    【解决方案3】:
    <?php
    $property = $property['post_content'];
    if (strlen($property) > 15) // if you want...
    {
        $maxLength = 14;
        $property = substr($property, 0, $maxLength);
    }
    echo $property;
    ?>
    

    【讨论】:

    • 如果他还想使用$property['post_content']$property数组的其他项怎么办?
    • 在第一行,他可以声明另一个变量 $postContent = $property['post_content'] 并使用它:)
    • 或者如果他再次需要,将整个数组存储在另一个变量中。
    猜你喜欢
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多