无法删除字符串中值的第二个实例


unable to remove 2nd instance of a value within a string

我知道str_replace( )会删除字符串的实例。

但是如何只删除字符串中的一个字符串实例。

下面是一个URL地址的例子,我只想删除例子的第一个实例Direcotry/'

www.example/exampleDirectory/exampleDirectory/index.php 

我需要首先测试示例目录/有两个实例,如果是,请删除其中一个。

$url  = www.example/exampleDirectory/exampleDirectory/index.php 
if ($url ==  ) 
{
  $newURL  = str_replace($url, "", "exampleDirectory/");
}

你犯了非常简单的错误,保罗。我也时不时地这样做。正确的参数顺序为:

str_replace($search, $replace, $subject)

最简单的方法:

$newURL = str_replace("/exampleDirectory/exampleDirectory", 
                      "/exampleDirectory", $url);

您可以通过查找第一个子字符串的偏移量和长度来执行此操作。要检查是否有多个实例,您可以使用substr_count()

$search = "exampleDirectory/";
// check so the string exists more than once
if (substr_count($url, $search) > 1) {
  $length = strlen($search);
  $offset = strpos($url, $search);
  // replace the first occurance of the string
  $newURL = substr_replace($url, "", $offset, $length);
}