I'm trying to extract portions of a URL in PHP using parse_url
and remove a portion of the [path]
if it exists.
For example, if my URL is "http://localhost/website/section/type/name/" and I want to remove the /website/
portion from the url [path]
:
$url = wp_get_referer(); // using WordPress to get referring URL
$parsed = parse_url($url);
$parsed = preg_replace('/website/', '', $parsed[path]);
If I echo $parsed
I get //section/type/name/
as the result, whereas I'd like to return simply section/type/name
as the result when "/website/" is present in the URL path string. How might I achieve this result?
preg_replace
is treating the /
characters as the expression delimiter.
Since your search term is not a regular expression, you can simply use str_replace
instead. Add in rtrim
to remove the trailing slash.
$parsed = rtrim(str_replace('/website/', '', $parsed['path']), '/');
Note that I've also quoted the path
parameter so as not to trigger an "unknown constant" notice