删除用冒号分隔的字符串的最后一部分


Removing last part of string divided by a colon

我有一个字符串,看起来有点像,world:region:bash

它划分文件夹名称,这样我就可以为FTP函数创建一个路径。

然而,在某些情况下,我需要能够删除字符串的最后一部分,例如

我有这个world:region:bash

我需要这个world:region

脚本无法知道文件夹名称是什么,因此它需要能够删除最后一个冒号之后的字符串。

$res=substr($input,0,strrpos($input,':'));

我可能应该强调,strrpos而不是strpos在给定字符串中查找子字符串的最后一次出现

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

您可能想尝试以下操作:

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

或者。。。如果你使用这些信息创建一个函数,你会得到这个:

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

分解字符串,并移除最后一个元素。如果您再次需要字符串,请使用内爆。

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

使用正则表达式/:[^:]+$/,preg_replace

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

演示

请注意$(意思是字符串终止)是如何使用的。

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