-1

How to get all letters without the last part of string, for example:

$string = 'namespace\name\driver\some\model';

The expected output is:

namespace\name\driver\some\
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Michał Ziembiński
  • 1,124
  • 2
  • 10
  • 31

5 Answers5

1

Use explode() to split the string by \ and then implode() to join the new string:

echo implode('\\', array_slice(explode('\\', $string), 0, -1));

Or use a regular expression to replace everything after the last slash:

echo preg_replace('#[^\\\\]*$#', '', $string);

Output:

namespace\name\driver\some
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

If you need to you take a substring, no need to mess with explodes/implodes/array...

Try this basic thing:

$string = substr($string, 0, strrpos($string, '\\') + 1);
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Ejzy
  • 400
  • 4
  • 13
1

assuming you are using php,

use this,

<?php
$string ='namespace\name\driver\some\model';
$output= implode('\\', array_slice(explode('\\', $string), 0, -1));
?>
Ronak K
  • 1,567
  • 13
  • 23
1

Could you try using a regular expression? '.*\\'

Stuart Miller
  • 647
  • 3
  • 8
1

Find postion of slash frm the right - you have to escape it with additional \

<?php
$string = "namespace\name\driver\some\model";
$lastslash = strrpos($string,"\\") + 1;
$new_string = substr($string,0,$lastslash);
echo "new string - ".$new_string." ".$lastslash;    
?>
Leszek
  • 11
  • 1