1

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.

3
  • Is the value always static? A regex such as ((\d{2})\d{2})-\2(\d{2}) might be useful, replace with \1-\3. Commented May 29, 2016 at 15:39
  • no it's dynamic, I have taken a sample scenario only @chris85 Commented May 29, 2016 at 19:12
  • With substr you will need to make two calls, regex isn't usable? Commented May 29, 2016 at 21:54

3 Answers 3

3

str_replace would be easier to use:

$str = '2010-2011';
$replaced = str_replace('-20', '-', $str);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.