如何在php中删除字符串部分

时间:2016-05-29 15:23:24

标签: php string

我有一个字符串 2010-2011 ,我希望得到这样的结果 2010-11 ,使用我试过的php的substr()方法,但{{1虽然我已尝试过其他帖子,但无法获得准确的输出。

3 个答案:

答案 0 :(得分:3)

str_replace会更容易使用:

$str = '2010-2011';
$replaced = str_replace('-20', '-', $str);

答案 1 :(得分:2)

您可以使用substr两次,首先获得前五位数,然后使用第二位获得最后两位数。

<?php
$string = "2010-2011";

echo substr($string, 0, 5) . substr($string, -2);

参见示例:https://eval.in/578870

答案 2 :(得分:1)

使用正则表达式(preg_replace),如下所示:

        <?php
            $string         = "2010-2011";
            $desiredString  = preg_replace("#(2010)(\-)(20)(\d{2})#", "$1$2$4", $string);

            echo $desiredString; // DISPLAYS: 2010-11;