PHP code example of wpscholar / url

1. Go to this page and download the library: Download wpscholar/url library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wpscholar / url example snippets


use wpscholar\Url;

// Create from a URL string
$url = new Url('https://example.com/path?param=value#section');

// Get the current URL
$currentUrl = new Url(); // Automatically uses current URL

// Access URL components
echo $url->scheme; // 'https'
echo $url->host; // 'example.com'
echo $url->path; // '/path'
echo $url->query; // 'param=value'
echo $url->fragment; // 'section'

// Modify query parameters
$url->addQueryVar('new_param', 'value');
$url->removeQueryVar('old_param');

// Get specific query parameter
$value = $url->getQueryVar('param_name');

// Get all query parameters as array
$params = $url->getQueryVars();

// Get current URL
$currentUrl = Url::getCurrentUrl();

// Get current scheme (http/https)
$scheme = Url::getCurrentScheme();

// Strip query string from URL
$cleanUrl = Url::stripQueryString($url);

// Build URL from parts
$url = Url::buildUrl([
    'scheme' => 'https',
    'host' => 'example.com',
    'path' => '/path',
    'query' => 'param=value'
]);

// Given URL: https://example.com/blog/2023/post-title

// Get all path segments as array
$segments = $url->getSegments();
// Returns: ['blog', '2023', 'post-title']

// Get specific segment by index (zero-based)
$year = $url->getSegment(1);     // Returns: '2023'
$section = $url->getSegment(0);  // Returns: 'blog'
$slug = $url->getSegment(2);     // Returns: 'post-title'

// Get full URL as string - multiple methods:
$url = new Url('https://example.com/path?param=value');

// Method 1: Using toString()
echo $url->toString();  // 'https://example.com/path?param=value'

// Method 2: Cast to string directly
echo (string) $url;     // 'https://example.com/path?param=value'

// Method 3: Using magic __toString()
echo $url;              // 'https://example.com/path?param=value'

// Get URL parts as array
$urlParts = $url->toArray();  // Returns array of URL components