Tamaghna Banerjee
Tamaghna Banerjee

Reputation: 168

How to remove string part in php

I have a string 2010-2011, I would like to get result like this 2010-11, using php's substr() method I have tried but substr('2010'.'-'.'2011',0,7) not been able to get exact output, though I have tried from other posts.

Upvotes: 1

Views: 78

Answers (3)

kamal pal
kamal pal

Reputation: 4207

You can use substr twice, first to get first five digits and second to get last two.

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

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

see example: https://eval.in/578870

Upvotes: 2

Poiz
Poiz

Reputation: 7617

Use Regular Expression (preg_replace) instead like so:

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

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

Upvotes: 1

Mureinik
Mureinik

Reputation: 310993

str_replace would be easier to use:

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

Upvotes: 3

Related Questions