如何删除特定字符之前的子字符串?

How to remove substring up to a certain character?

我们有一个字符串不断生成以下模式。理想情况下,我们希望摆脱找到的第一个“/”之前的字符串(所有字符)。我尝试了以下但它不起作用。需要帮助看看我缺少什么。

目标是从开头删除第一个“/”和“/”本身之前的所有字符。棘手的部分是第一个“/”之前的字符串的长度可能会有所不同。

示例字符串:

  1. test-item/test-test1/test-2/test
  2. test-item2/test
  3. abdc/test/test/test

我试过的示例代码(其中 $str 是上面的示例字符串):

$patt = '/.+\/';
$repl = '';
$str = preg_replace($patt, $repl, $str);

当前输出:

  1. 测试
  2. 测试
  3. 测试

所需的字符串输出:

  1. test-test1/test-2/test
  2. 测试
  3. test/test/test

试试这个:

$exp = explode("/", "test-item/test-test1/test-2/test");
$result = implode(array_shift($exp), "/");

对于您拥有的每条路径。

你可以这样做:

$str = preg_replace('^.*?\/(.*)\/.*$', '', $str);

我同意@DragonSpirit: $str = substr($str, strpos($str, '/') + 1 );应该可以!

这是一个使用 substr() 和 strpos() 函数的方法:

 $str = substr($str, strpos($str, '/') + 1 );

这适用于您拥有的所有示例 - 祝您好运

<?php
$string = 'test-item/test-test1/test-2/test';
$character   = '/';
$position = strpos($string, $character);


    $string2 = substr($string, $position+1);    
    echo "New string is '$string2'";
?>