2

I'm trying to remove all data from the string after and including the "/"

$price="10/3"

I have tried preg_replace

$str = '2016/19';
$change = str_replace('/','-',$str);
$pattern = '/-*/';  
$new = preg_replace($pattern,'',$change);

I tried doing it the way above because didn't know if there was issues with slashes so I changed the string to 2016-19 and then tried to replace the pattern But it doesn't remove the data following the -it simply removes the -

Also I can't do a substr because the amount of digits before the / and after change

Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38

2 Answers2

3
$str = '2016/19';
$result = (explode("/", $str)[0]); //get the part before "/" after splitting

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

online Thomas
  • 8,864
  • 6
  • 44
  • 85
3

You were nearly right.

$str = '2016/19';
// escape "/" by using "\/"
// .*$ matches any character up to the end of the string denoted by "$"
$pattern = '/\/.*$/';
$new = preg_replace($pattern,'',$str);

echo $new;
maxhb
  • 8,554
  • 9
  • 29
  • 53
  • Regular expressions need to be enclosed by a starting and matching ending character. Most people use "/" like in the example above. Indeed many characters can be used which makes this a valid regex, too: "#/.*$#". No need to escape "/" here. – maxhb Jan 06 '16 at 11:41
  • BRILLIANT ! knew it was something simple I was missing ! – Chris Yates Jan 06 '16 at 11:44