Extract specific part of a string in PHP

前端 未结 4 1714
一整个雨季
一整个雨季 2021-01-14 01:03

I was simply wondering what would be the simplest and most efficient way of extracting a certain part of a dynamic string in PHP?

Per example, in this string:

<
相关标签:
4条回答
  • 2021-01-14 01:26

    The parse_url() function and extract the path. Explode on '/' and get the last element

    0 讨论(0)
  • 2021-01-14 01:28

    One of the following:

    preg_match('~/[^/]*$~', $str, $matches);
    echo $matches[0];
    

    Or:

    $parts = explode('/', $str);
    echo array_pop($parts);
    

    Or:

    echo substr($str, strrpos($str, '/'));
    
    0 讨论(0)
  • 2021-01-14 01:43

    Try this

    $url = $_SERVER['REQUEST_URI'];
    $parsed_url = parse_url($url);
    $url_parts = explode('/',$parsed_url['path']);
    print_r($url_parts);
    
    0 讨论(0)
  • 2021-01-14 01:48

    Try parse_url over regex:

    $segments = explode('/', parse_url($url, PHP_URL_PATH));
    

    $segments will be an array containing all segments of the path info, e.g.

    Array
    (
        [0] => 
        [1] => video
        [2] => xclep1_school-gyrls-something-like-a-party_music
    )
    

    So you can do

    echo $segments[2];
    

    and get

    `xclep1_school-gyrls-something-like-a-party_music`
    
    0 讨论(0)
提交回复
热议问题