$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)));
Related
I have some very long URL variables. Here is one example.
http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Ultimately it would be nice if I could find a way to use preg_replace to simply change one variable even if in the middle of the string for instance in the string above change print=no to 'print=yes for example.
I will however settle for a preg_replace pattern match that allows me to delete ?image=XYZ_1555025022.jpg. as this is a variable the name could be anything. It will always have "?image" " at the start and end with "&"
I think one of the problems I have run into is that preg_match seems to have issues on strings with "=" contained in them .
I am completely lost here in this and all those characters make may head spin. Maybe someone can give some guidance please?
Here's a demo of how you can do some of things you want using explode, parse_str and http_build_query:
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
// split on first ?
list($path, $query_string) = explode('?', $url, 2);
// parse the query string
parse_str($query_string, $params);
// delete image param
unset($params['image']);
// change the print param
$params['print'] = 'yes';
// rebuild the query
$query_string = http_build_query($params);
// reassemble the URL
$url = $path . '?' . $query_string;
echo $url;
Output:
http://localhost/index.php?mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=yes&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Demo on 3v4l.org
You can use str_replace() or preg_replace() to get your job done, but parse_url() with parse_str() will give you more controls to modify any parameters easily by array index. Finally use http_build_query() to make your final url after modification.
<?php
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo "BEFORE".PHP_EOL;
print_r($query);
$query['print'] = 'yes';
echo "AFTER".PHP_EOL;
print_r($query);
?>
DEMO: https://3v4l.org/npGij
I have a string like this being entered into my database that I can't format before it gets stored :
image/upload/v1440427262/hglz466d8mm1pazysaoh.jpg#32e2e9a111a4f9f4aa01dbad2ca2aa403c994d28
The only part of that string that I want to use is this :
hglz466d8mm1pazysaoh.jpg
I'm trying to use strpos to remove the excess data.
So far I've managed to remove everything after and including the hashtag
($data is the original string) :
$dataclean = substr($data, 0, strpos($data, "#"));
This works as expected with $dataclean returning :
image/upload/v1440427262/hglz466d8mm1pazysaoh.jpg
But I don't know how to remove the rest of the excess data :
image/upload/v1440427262/
Also, can this all be done in one hit or does it have to be split into several operations?
Use basename:
$dataclean = basename(substr($data, 0, strpos($data, "#")));
If basename() doesn't work I would explode the string by the forward slash.
$data = 'image/upload/v1440427262/hglz466d8mm1pazysaoh.jpg#32e2e9a111a4f9f4aa01dbad2ca2aa403c994d28';
$pieces = explode("/", $data);
$dataclean = substr($pieces[3], 0, strpos($data, "#"));
As mentioned in the question, first remove values after # using
$link = substr($data, 0, strpos($data, "#"));
Then use basename() function to access filename from the URL.
For example,
$link = "http://example.com/folderPath/filename.php";
echo basename($link); // It will return filename.php
Nothing wrong with substr + strpos, but it looks like your string is a URL, so you could use parse_url to isolate the path before using basename. Just another option FYI.
basename(parse_url($yourString, PHP_URL_PATH));
You can use a regex function:
preg_match("/[a-z0-9]+\.[a-z]{3}/i", $input_line, $output_array);
Try the code
Let say I've this URL:
http://example.com/image-title/987654/
I want to insert "download" to the part between "image-title" and "987654" so it would look like:
http://example.com/image-title/download/987654/
help would be greatly appreciated! thank you.
Assuming your URIs will always be the same (or at least predictable) format, you can use the explode function to split the URI into each of its parts, and then use array_splice to insert elements into that array, and finally use implode to put it all back together into a single string.
Note that you can insert elements into an array by specifying the $length parameter as zero. For example:
$myArray = array("the", "quick", "fox");
array_splice($myArray, 2, 0, "brown");
// $myArray now equals array("the", "quick", "brown", "fox");
There are a number of ways to do this in PHP:
Split and reconstruct using explode(), array_merge, implode()
Using substring()
Using a regular expression
Using str_replace
Assuming all the url's conform to the same structure (image-title/[image_id]) i recommend using str_replace like so:
$url = str_replace('image-title', 'image-title/download', $url);
If however image-title is dynamic (the actual title of the image) i recommend splitting and reconstructing like so:
$urlParts = explode('/', $url);
$urlParts = array_merge(array_slice($urlParts, 0, 3), (array)'download', array_slice($urlParts, 3));
$url = implode('/', $urlParts);
Not very well formatted, but i think this is what you need
$mystr= 'download';
$str = 'http://example.com/image-title/987654/';
$newstr = explode( "http://example.com/image-title",$str);
$constring = $mystr.$newstr[1];
$adding = 'http://example.com/image-title/';
echo $adding.$constring; // output-- http://example.com/image-title/download/987654/
i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.
I need to search for
src="http://www.domain.com/wp-content/uploads/2010/12/6a00e54fa8abf788330147e0622c2e970b-800wi.jpg"
and get
"http://www.domain.com/wp-content/uploads/2010/12/"
Since I never know how long the string is I need to get everything up to the last /
have a look at pathinfo()
ETA due to question edit:
#Chris: what you're trying to do is parse the DOM and pull out the values of src attributes. The easiest and most foolproof way to do this is to use a DOM parser. Have a look at DomDocument::loadHTML and the rest of the DOMDocument class.
Use stripos()
$val = substr($url, 0, stripos($url, '/'));
how about this:
$str = 'src="http://www.domain.com/wp-content/uploads/2010/12/6a00e54fa8abf788330147e0622c2e970b-800wi.jpg"';
$str = substr($str,5);
$str = substr($str,0,-1);
echo dirname($str)."/";
You can loop the string in reverse and look for the 1st '\' that you encounter, mark it's position, then copy the string up to that point into another string.
$resulted_path = "";
for($i = strlen($str)-1 ; ($i>=0) && ($str{$i} != '/') ; $i --);
strncpy($resulted_path, $str, $i);
Do not forget the ';' after the for loop.
The resulting string should contain your desired string.
References:
charAt |
strncpy |
strlen