replace VARIABLE in $url string - php

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

Related

How To Output User Submitted Links On Your Webpage Securely?

I want to allow my website visitors (any Tom, Dick & Harry) submit their links to my webpage for output on my page.
I need to parse user submitted urls before echoing their submitted urls on my page. Need to parse the urls as I won't know what urls they will be submitting nor the structures of their urls.
A user could theoretically visit my page and inject some Javascript code using, for example:
?search=<script>alert('hacked')</script>
You understand my point.
I got to write php script that when users submit their urls, then my php script parses their urls and encodes them by adding urlencode, rawurlencode, intval in the appropriate places before outputting them via htmlspecialchars.
Another wrote this following script. Problem is, it outputs like so:
http%3A%2F%2Fexample.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13
It should output like this:
http://example.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=13
This is their code ....
Third Party Code:
<?php
function encodedUrl($url){
$query_strings_array = [];
$query_string_parts = [];
// parse URL & get query
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query_strings = parse_url($url, PHP_URL_QUERY);
// parse query into array
parse_str($query_strings, $query_strings_array);
// separate keys & values
$query_strings_keys = array_keys($query_strings_array);
$query_strings_values = array_values($query_strings_array);
// loop query
for($i = 0; $i < count($query_strings_array); $i++){
$k = urlencode($query_strings_keys[$i]);
$v = $query_strings_values[$i];
$val = is_numeric($v) ? intval($v) : urlencode($v);
$query_string_parts[] = "{$k}={$val}";
}
// re-assemble URL
$encodedHostPath = rawurlencode("{$scheme}://{$host}{$path}");
return $encodedHostPath . '?' . implode('&', $query_string_parts);
}
$url1 = 'http://example.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=13';
$url2 = 'http://example.com/autos/cars/list.php?state=california&max_price=50000';
// run urls thru function & echo
// run urls thru function & echo
echo $encoded_url1 = encodedUrl($url1); echo '<br>';
echo $encoded_url2 = encodedUrl($url2); echo '<br>';
?>
So, I changed this of their's:
$encodedHostPath = rawurlencode("{$scheme}://{$host}{$path}");
to this of mine (my amendment):
$encodedHostPath = rawurlencode("{$scheme}").'://'.rawurlencode("{$host}").$path;
And it seems to be working. As it's outputting:
http://example.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=13
QUESTION 1:
But I am not sure if I put the raw_urlencode() in the right places or not and so best you check.
Also, should not the $path be inside raw_urlencode like so ?
raw_urlencode($path)
Note however that:
raw_urlencode($path)
doesn't output right.
QUESTION 2:
I FURTHER updated their code to a new VERSION and it's not outputting right. Why is that ? Where am I going wrong ?
All I did was add a few lines.
This is my update (NEW VERSION) which outputs wrong. Outputs like this:
http%3A%2F%2Fexample.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13
I added a few lines of my own at the bottom of their code.
MY UPDATE (NEW VERSION):
<?php
function encodedUrledited($url){
$query_strings_array = [];
$query_string_parts = [];
// parse URL & get query
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query_strings = parse_url($url, PHP_URL_QUERY);
// parse query into array
parse_str($query_strings, $query_strings_array);
// separate keys & values
$query_strings_keys = array_keys($query_strings_array);
$query_strings_values = array_values($query_strings_array);
// loop query
for($i = 0; $i < count($query_strings_array); $i++){
$k = urlencode($query_strings_keys[$i]);
$v = $query_strings_values[$i];
$val = is_numeric($v) ? intval($v) : urlencode($v);
$query_string_parts[] = "{$k}={$val}";
}
// re-assemble URL
$encodedHostPath = rawurlencode("{$scheme}").'://'.rawurlencode("{$host}").$path;
return $encodedHostPath . '?' .implode('&', $query_string_parts);
}
if(!ISSET($_POST['url1']) && empty($_POST['url1']) && !ISSET($_POST['url2']) && empty($_POST['url2']))
{
//Default Values for Substituting empty User Inputs.
$url1 = 'http://example.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=138';
$url2 = 'http://example.com/autos/cars/list.php?state=california&max_price=500008';
}
else
{
//User has made following inputs...
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
//Encode User's Url inputs. (Add rawurlencode(), urlencode() and intval() in user's submitted url where appropriate).
$encoded_url1 = encodedUrledited($url1);
$encoded_url2 = encodedUrledited($url2);
}
echo $link1 = '<a href=' .htmlspecialchars($encoded_url1) .'>' .htmlspecialchars($encoded_url1) .'</a>';
echo '<br/>';
echo $link2 = '<a href=' .htmlspecialchars($encoded_url2) .'>' .htmlspecialchars($encoded_url2) . '</a>';
echo '<br>';
?>
This thread is really about the 2nd code. My update.
Thank You!
I fixed my code.
Answering my own question.
Fixed Code:
function encodedUrledited($url){
$query_strings_array = [];
$query_string_parts = [];
// parse URL & get query
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query_strings = parse_url($url, PHP_URL_QUERY);
// parse query into array
parse_str($query_strings, $query_strings_array);
// separate keys & values
$query_strings_keys = array_keys($query_strings_array);
$query_strings_values = array_values($query_strings_array);
// loop query
for($i = 0; $i < count($query_strings_array); $i++){
$k = $query_strings_keys[$i];
$key = is_numeric($k) ? intval($k) : urlencode($k);
$v = $query_strings_values[$i];
$val = is_numeric($v) ? intval($v) : urlencode($v);
$query_string_parts[] = "{$key}={$val}";
}
// re-assemble URL
$encodedHostPath = rawurlencode($scheme).'://'.rawurlencode($host).$path;
$encodedHostPath .= '?' .implode('&', $query_string_parts);
return $encodedHostPath;
}
if(!ISSET($_POST['url1']) && empty($_POST['url1']) && !ISSET($_POST['url2']) && empty($_POST['url2']))
{
//Default Values for Substituting empty User Inputs.
$url1 = 'http://example.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=138';
$url2 = 'http://example.com/autos/cars/list.php?state=california&max_price=500008';
}
else
{
//User has made following inputs...
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
//Encode User's Url inputs. (Add rawurlencode(), urlencode() and intval() in user's submitted url where appropriate).
}
$encoded_url1 = encodedUrledited($url1);
$encoded_url2 = encodedUrledited($url2);
$link1 = '<a href=' .htmlspecialchars($encoded_url1) .'>' .htmlspecialchars($encoded_url1) .'</a>';
$link2 = '<a href=' .htmlspecialchars($encoded_url2) .'>' .htmlspecialchars($encoded_url2) . '</a>';
echo $link1; echo '<br/>';
echo $link2; echo '<br/>';
?>
These 2 following lines were supposed to be outside the ELSE. They weren't. Hence all the issue. Moved them outside the ELSE and now script working fine.
$encoded_url1 = encodedUrledited($url1);
$encoded_url2 = encodedUrledited($url2);

How to strip text from string if contained

I have a string $current_url that can contain 2 different values:
http://url.com/index.php&lang=en
or
http://url.com/index.php&lang=jp
in both cases I need to strip the query part so I get: http://url.com/index.php
How can I do this in php?
Thank you.
Simplest Solution
$url = 'http://url.com/index.php&lang=en';
$array = explode('&', $url);
echo $new_url =$array[0];
To only remove the lang query do this
$url = 'http://url.com/index.php&lang=en&id=1';
$array = explode('&lang=en', $url);
echo $new_url = $array[0] .''.$array[1];
//output http://url.com/index.php&id=1
So this way it only removes the lang query and keep other queries
If the value of your lang parameter is always of length 2, which should be the case for languages, you could use:
if(strpos($current_url, '&lang=') !== false){
$current_url = str_replace(substr($current_url, strpos($current_url, '&lang='), 8), '', $current_url);
}
If the substring "&lang=" is present in $current_url, it removes a substring of length 8, starting at the "&lang=" position. So it basically removes "&lang=" plus the 2 following chars.
You can Use strtok to remove the query string from url.
<?php
echo $url=strtok('http://url.com/index.php&lang=jp','&');
?>
DEMO
Answer based on comment.
You can use preg_replace
https://www.codexworld.com/how-to/remove-specific-parameter-from-url-query-string-php/
<?php
$url = 'http://url.com/index.php?page=site&lang=jp';
function remove_query_string($url_name, $key) {
$url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url_name);
$url = rtrim($url, '?');
$url = rtrim($url, '&');
return $url;
}
echo remove_query_string($url, 'lang');
?>
DEMO

How to remove last element in php [duplicate]

This question already has answers here:
Strip off specific parameter from URL's querystring
(22 answers)
Closed 8 years ago.
I have to remove the last element in a string. I used rtrim in php but it is not working.
This is the string:
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC
I need to remove "&make_order=ASC"
Can anyone help me?
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo substr($s, 0, strrpos($s, '&'));
Edit:
$url = $base_url.trim( $_SERVER['REQUEST_URI'], "&year_order=".$arr['year_order']."" );
// ^
// |_ replace , with .
trim should work:
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$string = trim($string, "&make_order=ASC");
There's no guarantee that make_order will be at the end of the query string - or exist at all. To remove the field properly, you'd have to use something like this:
$url = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
// break down the URL into a path and query string
$parsed = parse_url($url);
// turn the query string into an array that we can manipulate
$qs = array();
parse_str($parsed['query'], $qs);
// remove the unwanted field
unset($qs['make_order']);
// rebuild the URL
$rebuilt = $parsed['path'];
if(!empty($qs)) {
$rebuilt .= '?' . http_build_query($qs);
}
echo $rebuilt;
$actual_link = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo str_replace("&make_order=ASC","",$actual_link);
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$args = array_pop(explode($string, "&"));
$string = implode("&", $args);
There are a bunch of ways. The easiest might be:
$i=strrpos($text,'&');
$newstring=substr($text,0,$i);
$str = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo $str . "<br>";
echo trim($str,"&make_order=ASC");
if &make_order=ASC is always going to be at the end, you can use strstr() to do this
$str = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo strstr($str,'&make_order=ASC',true);
Remove desired key from url.
Use:
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo remove_key_from_url($url, 'make_order');
Output :
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100
Code:
function remove_key_from_url($url, $key) {
if (strpos($url, '?') === false) return $url;
list($left, $right) = explode('?', $url, 2);
parse_str($right, $get);
if (isset($get[$key])) unset($get[$key]);
return $left . '?' . http_build_query($get);
}

How can I find everything until something else in PHP and return that as a string?

I want to return these unique values from my URLs
394_black
500_mono2
The URLs:
/shop/swarovski/394_black_the-reagan-swarovski-maxi-dress
/shop/celeb/500_mono2_the-reagan-swarovski-maxi-dress
Can I do this in PHP?
Pseudo Code
$url = get url
$firstvar = after 3rd / and after second _ save text (500_mono2) from $url
$secondvar = using $firstvar return only first 3 numbers
//substr($firstvar, 0, 3); (I think this will be it)
Updated my Question above, easier to understand
<?php
$url = '/shop/celeb/500_mono2_the-reagan-swarovski-maxi-dress';
$urlparts = explode('/', $url);
list($var1, $var2, $var3) = explode('_', end($urlparts));
echo $var1 . '<br>' . $var2 . '<br>' . $var3;
?>

Strip array of url and other characters, show only post name

The xml is like this: (wordpress url's) I want to strip them and get only the posts words.
http://www.site1.com/dir/this-is-page/
http://www.site2.com/this-is-page
How do i strip the url's and get only "this is page" (without the rest of the urls, and the "-") if i have two diffrent types of urls; one with dir and one without dir? Sample code bellow:
$feeds = array('http://www.site1.com/dir/feed.xml', 'http://www.site2.com/feed.xml');
foreach($feeds as $feed)
{
$xml = simplexml_load_file($feed);
foreach( $xml->url as $url )
{
$loc = $url->loc;
echo $loc;
$locstrip = explode("/",$loc);
$locstripped = $locstrip[4];
echo '<br />';
echo $locstripped;
echo '<br />';
mysql_query("TRUNCATE TABLE interlinks");
mysql_query("INSERT INTO interlinks (title, url) VALUES ('$locstripped', '$loc')");
}
}
?>
TY
Ty guys, did it like this:
$urlstrip = basename($loc);
$linestrip = str_replace(array('-','_'), ' ', $urlstrip);
You want only the last segment of the URL?
Try something like this.
$url = trim('http://www.site1.com/dir/this-is-page/', '/');
$url = explode('/', $url);
$url = array_pop($url);
$url = str_replace(array('-','_'), ' ', $url);
It's not very elegant... but it works.
replace
$locstripped = $locstrip[4];
with
$locstripped = $locstrip[count($loc) - 1];
if(!$locstripped)
$locstripped = $locstrip[count($loc) - 2];
$locstripped = str_replace('-', ' ', $locstripped);

Categories