代码之家  ›  专栏  ›  技术社区  ›  Bhumi Shah

如何在PHP中获取针后字符串?

php
  •  2
  • Bhumi Shah  · 技术社区  · 9 年前

    我有如下字符串:

    $str = '/test/test1/test2/test3/testupload/directory/';
    

    现在我想获取一些尝试过的特定字符串:

    strstr($str, 'test3');
    

    但我想在打针后取值吗?我该怎么办?

    谢谢

    5 回复  |  直到 9 年前
        1
  •  2
  •   Uttam Kumar Roy    9 年前
    $str = '/test/test1/test2/test3/testupload/directory/';        
    $new_str = strstr($str, 'test3');
    // Use this to get string after test3 
    $new_str = str_replace('test3', '', $new_str); 
    // $new_str value will be '/testupload/directory/'
    
        2
  •  1
  •   user5134807 user5134807    8 年前

    为什么不构造一个helper函数呢。

    这是我之前做的一个(完全不是艺术攻击参考)。

    /**
     * Return string after needle if it exists.
     *
     * @param string $str
     * @param mixed $needle
     * @param bool $last_occurence
     * @return string
     */
    function str_after($str, $needle, $last_occurence = false)
    {
        $pos = strpos($str, $needle);
    
        if ($pos === false) return $str;
    
        return ($last_occurence === false)
            ? substr($str, $pos + strlen($needle))
            : substr($str, strrpos($str, $needle) + 1);
    }
    

    您可能已经注意到,此函数为您提供了在给定针的第一次或最后一次出现后返回内容的选项。下面是几个用例:

    $animals = 'Animals;cat,dog,fish,bird.';
    
    echo str_after($animals, ','); // dog,fish,bird.
    
    echo str_after($animals, ',', true); // bird.
    

    我倾向于创建一个全球 helpers.php 包含类似于此的函数的文件,我建议您也这样做-它使事情变得简单得多。

        3
  •  0
  •   Pupil    9 年前

    您可以找到的索引 test3 然后继续:

    <?php
    $str = '/test/test1/test2/test3/testupload/directory/';
    $find = 'test3'; // Change it to whatever you want to find.
    $index = strpos($str, $find) + strlen($find);
    echo substr($str, $index); // Output: /testupload/directory/
    ?>
    

    或使用 测试3 找出最后一个元素。

    <?php
    $str = '/test/test1/test2/test3/testupload/directory/';
    $find = 'test3'; // Change it to whatever you want to find.
    $temp = explode($find, $str);
    echo end(explode($find, $str));
    ?>
    
        4
  •  0
  •   user3785693 user3785693    9 年前

    尝试

    <?php
    $str = '/test/test1/test2/test3/testupload/directory/';
    $position = stripos($str, "test3");
    if ($position !== false) {
        $position += strlen("test3");
        $newStr = substr($str, $position);
        echo "$newStr";
    } else {
        echo "String not found";
    }
    ?>
    
        5
  •  0
  •   Andreas    9 年前

    也可以使用preg_match()完成

    preg_match("/test3\/(.*)/", $str, $output);
    Echo $output[1];
    

    使用preg_match,只需一行即可获得所需的部件。
    模式搜索 test3 和a / 之后,但因为 / 需要逃离那里 \/ .
    然后 (.*) 表示匹配所有内容,直到字符串结束。
    输出[0]将完全匹配“test3/testupload…”。
    输出[1]只是您想要的“testwupload/…”部分。