Replace certain part of a string - php

How can I replace a certain part of a string. For example we have the URL:
username=[LINK]&quantity=10&limit=[POSTS]&interval=5&url=https://google.com/&service=762&runs=[RUNS]&type=Comments
I want to keep the parameters, quantity=\, limit=, interval=* & runs=*.
I've tried to do it with parsing but can't get it work,
parse_str($p_api, $query);
$quantity = '&quantity='.$query['quantity'];
$limit = '&limit='.$query['limit'];
$interval = '&interval='.$query['interval'];
$runs = '&runs='.$query['runs'];
How can I update all other data but keep these parameters as they are in the default string?

you can parse query parse_str(), update array value you wish and http_build_query() for url encoding
$str = "username=[LINK]&quantity=10&limit=[POSTS]&interval=5&url=https://google.com/&service=762&runs=[RUNS]&type=Comments";
parse_str($str,$query);
$query['username'] = "xyz";
$query['type'] = "post";
echo http_build_query($query);
Demo

Related

PHP/MYSQL/JSON: Parse complicated string or reassemble as dictionary

I receive a complicate string through JSON that represents an object:
<Offers: 0x170483070> (entity: Offers; id: 0xd00000000b880006 <x-
coredata://03C4A684-2218-489C-9EF6-42634ED10552/Offers/p738> ; data: {\\n
topic = nil;\\n topid = 9403;\\n hasserverid = nil;\\n isprivate = nil;\\n
lasttouched = \\\"2018-07-08 16:49:01 +0000\\\";\\n lastviewed = nil;\\n
localid = 42;\\n needpicsync = nil;\\n needsync = nil;\\n secondorder
= 0;\\n oid = 0;\\n offer = test;\\n offerdone = nil;\\n offernumber =
70;\\n userid = 1;\\n wasdeleted = nil;\\n whenadded = \\\"2018-07-08
16:04:20 +0000\\\”;\\n})
I would like to save certain things to MYSQL. In the above example, I would like to save the fields offer and offernumber among others to a record with something like:
$sql = "INSERT into offers (offer,offernumber) VALUES ('test',70)";
To do this, of course, I first have to parse the string to get the value for offer, the one for offer number and ideally, the keys and values for the entire object.
Should I first convert the string into some sort of array,dictionary or data structure? Or should I try to parse the string using regex or some other method? If the latter, would appreciate suggestions on what what regex or technique to use.
Thanks in advance for any suggestions!
You can try to convert the string into a object with PHP,
this may help you:
$input = "**The input string**";
// Remove the escaped new lines
$jsonString = str_replace("\\n", "\n", substr($input, strpos($input, "data: ")+5));
$jsonString = substr($jsonString, 0, strlen($jsonString) - 1);
// Convert the equals, semicolons and remove the escaped backslash
$jsonString = str_replace(";", ",", $jsonString);
$jsonString = str_replace("=", ":", $jsonString);
$jsonString = str_replace('\\', '', $jsonString);
$matches = array();
// Use regex to get json key-value
if(preg_match_all('/(\w+)\s*\:\s*(.+)\s*\,/m', $jsonString, $matches,PREG_SET_ORDER, 0)){
// Iterate the matches and enclose key and value into double quotes
foreach($matches as $item){
// Enclose the value if isn't a number or a date
if(strpos(trim($item[2]), '"') !== 0 && !is_numeric($item[2])){
$item[2] = '"'.$item[2].'"';
}
// Replace in json string
$jsonString = str_replace($item[0], '"'.$item[1].'"'.' : '.$item[2].',', $jsonString);
}
}
// Remove last comma
$jsonString = substr($jsonString, 0, strlen($jsonString) - 3) . '}';
// Transform json string to object
$jsonObject = json_decode($jsonString);
// Show the json string
echo($jsonString);
// Display the object
var_dump($jsonObject);
the above code convert the given string to an object and then you can use the properties as you need.
you can try this here: PHP Sandbox

PHP - How to remove pagination page variable from URL?

I am tryign to remove pagination page ID from URL. For example I have URL looks like this:
$urlVal = "http://192.168.1.233/sitename/property-list?page=13&page=11&sproperty=for sale&srooms=1,10&scity=&scountry=&lat=31.0000000&long=35.0000000&sprice=100,100000";
And want to remove, If any of matches match from URL:
1. page=1
2. page=1&page=2
3. page=1&page=2$page=3
4. page=1&page=2$page=3$page=4
In my current pagination code, Previous page is concating everytime when page is changed thats why I want to remove all page.
I have used this code but not working well.
$urlVal = "http://192.168.1.233/sitename/property-list?page=13&page=11&sproperty=for sale&srooms=1,10&scity=&scountry=&lat=31.0000000&long=35.0000000&sprice=100,100000";
//$getUrl =$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$parts = parse_url($urlVal);
$urlVar = "";
$urlVar = $parts['query'];
echo $urlVar = preg_replace('/page=[0-9]&+/', '', $urlVar);
Try my code here: http://codepad.org/lSHV7a7w
I hope you understand what I am trying to do.
Thanks.
Try this.
$urlVal = "http://192.168.1.233/sitename/property-list?page=13&page=11&sproperty=for sale&srooms=1,10&scity=&scountry=&lat=31.0000000&long=35.0000000&sprice=100,100000";
$parts = parse_url($urlVal);
parse_str($parts['query'], $query);
unset($query['page']);
$newUrl = "{$parts['scheme']}://{$parts['host']}{$parts['path']}?" . http_build_query($query);
echo $newUrl;
// Regx Pattern
echo preg_replace('/&?page=[0-9]+&?/', '', $parts['query']);
How about using concatenation of numbers as page value?
$urlVal = "http://192.168.1.233/sitename/property-list?page=11,13&etc..."
It shortens url and makes removing parameter easy:
$urlVar = preg_replace('/page=[0-9,]+&/', '', $urlVar);
You can extract them from url using:
preg_match("/page=([0-9,]+)&/", $urlVal, $m);
$pages = explode(",", $m[1]);

Remove character from php variable

I am trying to remove first 51 character of a long URL , I'm using
$sql = $db->Query(some query);
$mysite = $db->FetchArray($sql);
$str = $mysite['url'] ;
$str2 = substr('$str',51);
Above code return blank value, it works fine if i use plan text for $str
e.g.
$str = "I am looking for a way to pull the first 100 characters from a string"
$str2 = substr('$str',10);
my url is like "https://dl.dropbox.com/u/55299544/google.html?urlc=http://example.com"
i want to get http://example.com from database to show on user page,
how can i do this?
You're making this too complicated. If you are trying to get the http://example.com from the long URL then do this.
<?php
sql = $db->Query(some query);
$mysite = $db->FetchArray($sql);
$str = $mysite['url'] ;
$query = parse_url($str, PHP_URL_QUERY );
parse_str($query, $link);
echo $link["urlc"]; //http://example.com
?>

php special characters problem

I am having a problem with the special characters in my script:
This is what I have so far:
$curlstrip = explode("&", $data);
$filename = substr(htmlEntities($curlstrip[5]), 2);
and if $data contains any special charaters like ' which is ', then instead of getting the chunk of string that I need, I get only the first part.
A more detailed example:
$data = "12er&sdsretdgsd&file=Chris ' 19 &blabla"
the script will read the ' after Chris as ' and $curlstrip[5] will have a different value.
Hope is clear enough.
LE. Following this example:
$data = "12er&sdsretdgsd&file=Chris ' 19 &blabla"
$curlstrip = explode("&", $data);
$curlstrip[0] = '12er';
$curlstrip[1] = 'sdsretdgsd';
but
$curlstrip[2] = 'file=Chris' instead of 'file=Chris ' 19'
and that is because the ' is being read as
'
Thx,
Cristian.
Try:
$curlstrip = explode("&", html_entity_decode($data));
$filename = substr(htmlEntities($curlstrip[5]), 2);
As I cant replicate your error given the code supplied, I have a hunch- try:
$data=str_replace("'","'", $data);
$curlstrip = explode("&", html_entity_decode($data));
$filename = substr(htmlEntities($curlstrip[5]), 2);
If, for whatever reason, you have && (two ampersands) occurring in $data next to one another, it will interfere with the explode function.
Make htmlentities the last thing you call on the data.
$filename = htmlentities(substr($curlstrip[5], 2));
Aside from that there are functions to deal with what you're doing. parse_str will create an array from a query string. parse_url can be used to extract the query string from a url.

PHP update url in variable

$link = http://site.com/view/page.php?id=50&reviews=show
How can we add &extra=video after id=50?
id is always numeric.
url can have many other variables after ?id=50
&extra=video should be added before the first & and after the 50 (value of id)
It will be used this way:
echo 'Get video';
Thanks.
As Treffynnon says, the order seldomly matters. However, if you really need if for some reason, just use
parse_url to get the querystring
parse_str to create an array of parameter
array_splice to inject a parameter
http_build_query to rebuild a proper query string
This will do it for you
<?php
$linkArray = explode('&',$link);
$linkArray[0] += '&extra=video';
$link = implode('&',$linkArray);
?>
Explode will split the link string at every &, so it doesn't care how many elements you have in the url.
The first element, will be everything including the id=## before the first & sign. So we append whatever you want to appear after it.
We put our array together again as a string, separating each element by an &.
Is ID always the first post parameter? If so, then you could jsut do some sort of string manipulation. Use strpos($link, "&") to find out the position where you want to insert. Then do a few substr() based on that position and then append them all together. Its kind of hacky I know, but it will definitely work.
$pos = strpos($link, "&");
$first = substr($link, 0, $pos);
$last = substr($link, $pos);
$extra = "&extra=video";
$newLink = $first . $extra . $last;
See this link for some of the string manipulation functions that I mentioned above: http://us3.php.net/strings
i would suggest to use functions specifically aimed at url parsing, not general string functions:
$link = 'http://site.com/view/?id=50&reviews=show';
$query = array();
parse_str(parse_url($link, PHP_URL_QUERY), $query);
$query['extra'] = 'video';
$linkNew = http_build_url($link, array('query' => http_build_query($query)));

Categories