Removing the last part of a colon-separated string

I have a line that looks something like this: world:region:bash

It divides the folder names, so I can create a path for FTP functions.

However, I need to delete the last part of the line at some points, so for example,

I have this world:region:bash

I need to get world:region

the script will not be able to find out what the names of the folders are, so some of them should be able to delete the line after the last colon.

+4
source share
6 answers
 $res=substr($input,0,strrpos($input,':')); 

I should probably emphasize that strrpos not strpos finds the last occurrence of a substring in a given string

+17
source
 $tokens = explode(':', $string); // split string on : array_pop($tokens); // get rid of last element $newString = implode(':', $tokens); // wrap back 
+6
source

Expand the line and delete the last item. If you need a string again, use implode.

 $items = array_pop(explode(':', $the_path)); $shotpath = implode(':', $items); 
+2
source

You can try something like this:

 <?php $variable = "world:region:bash"; $colpos = strrpos($variable, ":"); $result = substr($variable, 0, $colpos); echo $result; ?> 

Or ... if you create a function using this information, you will get the following:

 <?php function StrRemoveLastPart($string, $delimiter) { $lastdelpos = strrpos($string, $delimiter); $result = substr($string, 0, $lastdelpos); return $result; } $variable = "world:region:bash"; $result = StrRemoveLastPart($variable, ":"); ?> 
+2
source

Use the regex /:[^:]+$/ , preg_replace

 $s = "world:region:bash"; $p = "/:[^:]+$/"; $r = ''; echo preg_replace($p, $r, $s); 

demo

Note that $ , which means line termination, is used.

+1
source
 <?php $string = 'world:region:bash'; $string = implode(':', explode(':', $string, -1)); 
0
source

Source: https://habr.com/ru/post/1433172/


All Articles