PHP - remove last part from URL - php

Good day to all!
I need to grab article's URL and modify it by deleting the last part of it (moving one level up).
Grabbing the current URL with Wordpress function <?php echo get_permalink( $post->ID ); ?>
Example of use. My current article's URL:
http://example.com/apples/dogs/coffee
Delete the last part of URL so it will be:
http://example.com/apples/dogs
(And with no slash at the end)
So this will return the current Wordpress URL:
Text
but how can I delete the last part of it?
Thanks in advance!

$url = 'http://example.com/apples/dogs/coffee';
$newurl = dirname($url);

Most of the answers written here would work, but it's a bad practice to parse a url using explode and RegExp. It's better to use the PHP function parse_url. In this case, you can't encounter a problem if the url changes. This code will omit the last part of the url's fragment.
Here's the code:
<?php
$url = 'http://example.com/apples/dogs/coffee';
$parsed_url = parse_url($url);
$fragment = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] : '';
$new_fragment = '';
if(!empty($fragment)){
$fragment_parts = explode('/', $fragment);
// Remove the last item
array_pop($fragment_parts);
// Re-assemble the fragment
$new_fragment = implode('/', $fragment_parts);
}
// Re-assemble the url
$new_url = $scheme . '://' . $host . $new_fragment;
echo $new_url;
?>

It looks like you are simply looking for a posts' parent. That being the case you need to use 'get_post_ancestors($post->ID)'.
From the wordpress codex...
</head>
<?php
/* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
$class = '';
/* is it a page */
if( is_page() ) {
global $post;
/* Get an array of Ancestors and Parents if they exist */
$parents = get_post_ancestors( $post->ID );
/* Get the top Level page->ID count base 1, array base 0 so -1 */
$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
/* Get the parent and set the $class with the page slug (post_name) */
$parent = get_page( $id );
$class = $parent->post_name;
}
?>
<body <?php body_class( $class ); ?>

This will do what you're asking -
echo implode('/',array_slice(explode('/',get_permalink( $post->ID )),0,-1))
but it's weak.
Only use as solution as simple as this if you can guarantee you won't have any additional stuff at the end of the URL that you need to keep.

There are many ways (explode, strpos and substr, regex). Using regex you can do something like this:
$url = 'http://example.com/apples/dogs/coffee';
$url = preg_replace('#/[^/]+?$#', '', $url);

Related

replace VARIABLE in $url string

I have a PHP code, which prints article from Wikipedia into my wordpress article. My problem is to replace VARIABLE in $url string
Let me explain my scenario.
VARIABLE is: post title of wordpress which have to be inserted in $url.
If single word in title, just insert it replacing VARIABLE in string in $url
if 2 words I need to replace the space (period) between words to %20
And the code, which solves it:
global $post;
$title = str_replace([" "], ["%20"], $post->post_title);
print $title;
This is the main php code I have. So what is the right way to get
<?php
$url =
"http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&titles=**VARIABLE**&format=json&explaintext&redirects&inprop=url&indexpageids";
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
$title = $data->query->pages->$pageid->title;
$string = $data->query->pages->$pageid->extract;
$getarticle = str_replace(
["==", "Biography", "References"],
["<br> <br>", "<b>Biography</b>", " "],
$string
);
print $getarticle;
?>
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&titles=$title&format=json&explaintext&redirects&inprop=url&indexpageids';
Parse the URL using parse_url function.
Get the query params using query key from the output of the above function.
Explode based on & and add your $title variable to titles key.
Implode the query string back and make your URL again.
Snippet:
<?php
$parsed_url = parse_url($url =
"http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&titles=**VARIABLE**&format=json&explaintext&redirects&inprop=url&indexpageids");
$params = [];
parse_str($parsed_url['query'], $params);
$title = 'Some example';// $data->query->pages->$pageid->title;
$params['titles'] = $title;
$parsed_url['query'] = http_build_query($params);
$url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path']. '?' . $parsed_url['query'];
echo $url;
Online Demo

Change Attribute Some Links on Content

I'm building plugin wordpress for change attribute some links on content of post. I have function like this :
public static function encrypt_link_content( $content ){
if ( strpos( $content, 'safelinkThis' ) !== false ) {
// get dom from string of content
$content = str_get_dom($content);
// find link with attribute data-role=safelinkThis
$all_links = $content('a[data-role=safelinkThis]');
$count_links = count($all_links);
$i = 0;
$_links = self::get_links_post($count_links);
foreach ($all_links as $a) {
$href = $a->href;
$encrypt = self::zi_encrypt($href);
$a->href = $_links[$i]."?link=".$encrypt;
$i += 1;
}
$content = (string) $content;
}
return $content;
}
That function is work, Attribute href of link have been changed.
example of content :
Find us on :
Go to facebook
Go to google
Go to Twitter
Will be change to like this :
Find us on :
Go to facebook
Go to google
Go to Twitter
I'm use http://code.google.com/p/ganon/ library to find dom in string.
Now
I have a custom table for store domain exception, The name is wp_sf_domain. I won't change a link if it have href attribute with domain exception from wp_sf_domain.
I know, I can use this
global $wpdb;
$sf_table_name = $wpdb->prefix . 'sf_domain';
foreach ($all_links as $a) {
$href = $a->href;
$aDomain = parse_url($href)['host'];
$record = $wpdb->get_results( "SELECT * FROM $sf_table_name WHERE domain='$aDomain'" );
if(count($record) == 0){
// change this link
}
}
But I think this is a bad practice if I have many links on content, I should check one by one to database.
How can I compare between host of link on content with list domain in database and change a link attribute href if host of link not include in database?

Change Language without leaving current page

I am trying to change languages but stay on the current page:
i.e:
www.myurl.com/english/aboutus.php
www.myurl.com/german/aboutus.php
www.myurl.com/french/aboutus.php
So only the language directory changes.
I have the following but can't get it to work:
<?php
$full_url = $_SERVER['FULL_URL'] ;
$temparray = explode(".com/",$full_url,2);
$englishtemp = $temparray[0] . ".com/english/" . $temparray[1];
$englishlink = "<a href=$englishtemp><img src=../images/english-flag.jpg></a>";
echo $englishlink;
?>
I get the url to change from '/french/aboutus.php' to '/english' but it doesn't remember the page name 'aboutus.php' and returns to the index page.
Could any one please help?
Use basename($_SERVER['PHP_SELF']) for the current page.
$englishtemp = "/english/" . basename($_SERVER['PHP_SELF']);
$englishlink = "<a href=$englishtemp><img src=../images/english-flag.jpg></a>";
echo $englishlink;
See PHP documentation on $_SERVER.
Try this instead. It will generate links for all the languages except the current selected one :)
<?php
$full_url = $_SERVER['REQUEST_URI']; //select full url without the domain name
$languages = array('english', 'french', 'german'); //array of all supported languages
$url_bits = explode('/', $full_url); //divide url into bits by /
$current_language = $url_bits[1]; //current language is held in the second item of the array
//find current language in the array and remove it so we wouldn't have to display it
unset($languages[array_search($current_language, $languages)]);
$links = '';
foreach ($languages as $language) {
//generate links with images for the rest of the languages
$links .= '<img src="../images/' . $language . '-flag.jpg" title="'.ucfirst($language).'" />';
}
echo $links;
?>

Using an expression to remove part of a string

This is probably simple however I am not the best with expressions..
I am trying to get the following string from..
http://www.yoursite.com/offers/838?&SITEID=2172
to this.. using an expression that will remove the ?&SITEID and the dynamic id which will vary
http://www.yoursite.com/offers/838
Can anyone suggest the best/simplest method to do this?
Check this function:
$str = 'http://www.yoursite.com/offers/838?&SITEID=2172';
function remove_query_arg($var, $url = NULL){
if(!$url){
$url = $_SERVER['REQUEST_URI'];
}
$parsed_url = parse_url($url);
$query_vars = explode('&', $parsed_url['query']);
foreach($query_vars as $key => $value){
$query_vars[$key] = explode('=', $query_vars[$key]);
$query_variables[$query_vars[$key][0]] = $query_vars[$key][1];
}
if(is_array($var)){
foreach($var as $value){
unset($query_variables[$value]);
}
}
elseif(is_string($var)){
unset($query_variables[$var]);
}
$query_vars = array();
foreach($query_variables as $key => $value){
$query_vars[] = $key.($value !== NULL || !empty($value) ? '='.$value : '');
}
$query_str = '';
$query_str = implode('&',$query_vars);
return (isset($parsed_url['scheme']) && !empty($parsed_url['scheme']) ? $parsed_url['scheme'].'://' : '').$parsed_url['host'].(isset($parsed_url['path']) && !empty($parsed_url['path']) ? $parsed_url['path'] : '').(!empty($query_str) ? '?'.$query_str : '');
}
echo remove_query_arg('SITEID', $str);
This is a URL, so parse it as one, with parse_url().
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
$parts = parse_url($url);
$url = $parts["scheme"] . "://" . $parts["host"] . $parts["path"];
Using explode function returns an array
$url=http://www.yoursite.com/offers/838?&SITEID=2172
$result=explode('?',$url)
print_r($result);
output
array
{
[0]=>http://www.yoursite.com/offers/838
[1]=>?&SITEID=2172
}
A valid URL only has one ? so you can just use explode to break it into 2 parts
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
list($path, $query) = explode("?", $url, "2");
var_dump($path);
Output
string 'http://www.yoursite.com/offers/838' (length=34)
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
$str = substr($url, strpos($url, 0, "?&SITEID"));
// $str results in "http://www.yoursite.com/offers/838"
If you want to keep the part before the ? you can search
^(.+?)(\?&SITEID|$)
and replace with
$1
You search non greedily from the beginning of the line ^ to the first ?&SITEID and leave out the rest. If no ?&SITEID is found you get the entire line by arriving at the end of the string with $
| is the OR operator that tells the regex "Stop at the first ?&SITEID or at the end of the string"
EDIT:
After the comment where you explain your need to keep the rest of the querystring I suggest you a different approach: find
&?SITEID=[^&\s]+
being
&? an optional & at the beginning of the string
SITEID= the string you are looking for followed by
[^&\s]+ any number of non&, nonspace character
and remove it from the string. However, being this the case, I'd go with a non-regex, url-specific approach like suggested in the other answers.

How to detect a URL which has additional text at the end?

I am currently designing a website which uses this: <li class="current">.
I have gotten a script to detect when it's on said page to output the right class, however, when on the gallery.php?dir=thedir page, it fails to output the class!
Here's what I have so far, which is not working...
$ispage = preg_match_all('gallery.php/\[(.+?)\]/s');
I would appreciate any information somebody could give me :).
Full code:
<?php
$ispage = preg_match_all('gallery.php/\[(.+?)\]/s');
$currentpage = $_SERVER['REQUEST_URI'];
if ($ispage==$currentpage) {
echo '<li class="current">';
} else {
echo '<li>';
}
?>Photos</li>
Can't you use $_SERVER['SCRIPT_NAME'] or $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'] along with php function strpos($haystack, $findme)? It should make your life easy.
http://php.net/manual/en/function.strpos.php
It seems like $_SERVER['PHP_SELF'] is the one you need, it return the relative filename, without params.
Have a look here : http://www.php.net/manual/en/reserved.variables.server.php
If I understood your question you are trying to access query string values
Try echo $_GET['dir'];
EDIT
Tried this?
$ispage = '/'.basename($_SERVER['PHP_SELF']).'?'.($_SERVER['QUERY_STRING']);
$curepage = $_SERVER['REQUEST_URI'];
I think you need to define an array of links to solve your problem
so that
$curpage = $_SERVER['REQUEST_URI'];
$links = array('/gallery.php?dir=thedir', '/home.php?dir=anotherdir');
foreach($links as $link) {
$class = '';
if($link == $curpage) {
$class = 'class="current"';
echo '<li '.$class.'>';
.... rest of the code ....
}
}
<?php
$currentpage = $_SERVER['REQUEST_URI'];;
preg_match('/[^.]+\.[^.]+$/', $currentpage, $matches);
if ($matches[0] == "/gallery.php?dir=thedir") {
echo '<li class="current">';
} else {
echo '<li>';
}
?>Photos</li>
if a URL is something like: www.site.com/page.php?q=foo
then this
$currentpage = basename(__FILE__);
will just give you page.php
In addition, if you call it this way:
$currentpage = basename(__FILE__,".php");
will give you page
I'm pretty sure preg_match_all returns an int. If this is full code it won't be working at all. And yes, use something like $_SERVER['PHP_SELF']. Also you should think about using some better url to avoid this.

Categories