Question

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\
Was it helpful?

Solution

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);

OTHER TIPS

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

assuming you are using php,

use this,

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

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

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;    
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top