Assume that I have a URL like this
http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT1=Value
In this URL, TEXT1 at the end keeps changing for various pages. The Value will not change though. So it will be something like
For Page 1
http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT1=Value
For Page 2
http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT2=Value
For Page n
http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXTn=Value
How can I parametrize it? I tried something like this
for ($i=1;$i<=n;$i++)
{
$url = sprintf('http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT%d=Value',$i)
echo $url;
}
but it failed saying Sprintf too few arguments. Any suggestion, please?
You have more than one % sign in that url, sprintf parses it and tries to assign arguments to every %'something' it finds, you should escape the url encoded values.
You might want to check: http://www.php.net/manual/en/function.sprintf.php
Just use urldecode because the more than one (additional)% is creating problem .
$url=urldecode('http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT%d=Value');
$url = sprintf($url,$i);
$url = 'http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT'.$i.'=Value';
You can use the normal string also right, instead of using sprintf
for ($i=1 ; $i < = n ; $i++ )
{
$url = "http://subdomain.domain.com/folder1/abc?cat1=PTO2Cat2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&TEXT".$i."=Value";
echo $url;
}
I have got like this issue with using file_get_contents that get url query for solr search engine. I just solved it by escaping the % percent sign in the url encoded string by adding an extra % before every % in the string as follows:
$str = "%s?q=WebSite:%s&sort=Date%%20desc&version=2.2&start=%s&rows=%s&indent=on&wt=json";
return sprintf($str, $this->url, $this->website, $this->start, $rows);
Notice the double % after the Date in the string.
Related
sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);
I have a url like
test.php?x=hello+world&y=%00h%00e%00l%00l%00o
when i write it to file
file_put_contents('x.txt', $_GET['x']); // -->hello world
file_put_contents('y.txt', $_GET['y']); // -->\0h\0e\0l\0l\0o
but i need to write it to without encoding
file_put_contents('x.txt', ????); // -->hello+world
file_put_contents('y.txt', ????); // -->%00h%00e%00l%00l%00o
how can i do?
Thanks
You can get unencoded values from the $_SERVER["QUERY_STRING"] variable.
function getNonDecodedParameters() {
$a = array();
foreach (explode ("&", $_SERVER["QUERY_STRING"]) as $q) {
$p = explode ('=', $q, 2);
$a[$p[0]] = isset ($p[1]) ? $p[1] : '';
}
return $a;
}
$input = getNonDecodedParameters();
file_put_contents('x.txt', $input['x']);
Because the The $_GET and $_REQUEST superglobals are automatically run through a decoding function (equivalent to urldecode()), you simply need to re-urlencode() the data to get it to match the characters passed in the URL string:
file_put_contents('x.txt', urlencode($_GET['x'])); // -->hello+world
file_put_contents('y.txt', urlencode($_GET['y'])); // -->%00h%00e%00l%00l%00o
I've tested this out locally and it's working perfectly. However, from your comments, you might want to look at your encoding settings as well. If the result of urlencode($_GET['y']) is %5C0h%5C0e%5C0l%5C0l%5C0o then it appears that the null character that you're passing in (%00) is being interpreted as a literal string "\0" (like a \ character concatenated to a 0 character) instead of correctly interpreting the \0 as a single null character.
You should have a look at the PHP documentation on string encoding and ASCII device control characters.
i think you can use urlencode() to pass the value in URL and urldecode() to get the value.
if I have this url: node/95/pdf/1. How will I able to get the numeric/value 1? Tried the parse_url but gave me the wrong output.
PS: the value 1 is just an example, the id is dynamic depends on what the user click.
I would use sscanf
Untested example:
list($node_id, $pdf_id) = sscanf($url, "node/%d/pdf/%d");
$node_id contains the node id, $pdf_id contains the pdf id. According to your comment: Yes, you can output it with e.g. echo $pdf_id;.
If you need them both in an array, you can remove the list() method, doing it like this:
$ids = sscanf($url, "node/%d/pdf/%d");.
This returns an array with both node and pdf id in $ids.
Finally, if you just need the pdf id, you could do
$id = sscanf($url, "node/95/pdf/%d");.
I just showed how to fetch both because I assumed you may need both numbers from your url.
Edit
seeing all the other answers after posting my solution, I am wondering why everyone is solving this with multiple functions when there is a function available that does exactly what he needs: parsing a string according to a format. This also leads to less sql-injection prone code IMHO. And it doesn't break something when the url gets extended or query strings are appended.
Edit 2
list($node_id, $sub, $sub_id) = sscanf($url, "node/%d/%[^/]/%d"); will get you the "pdf" and it's id separate instead of "node/%d/%s/%d". This is because char / is also matched by %s. Using %[^/] matches everything except the forward slash.
You can do this:
$id = end(explode('/', 'node/95/pdf/1'));
Example:
$arr = explode('/', 'node/95/pdf/1');
$id = end($arr);
echo $id; // 1
$url = "node/95/pdf/1";
// Find the last occurence of a slash, get everything after that.
$id = substr($url, strrpos($url, "/") + 1 );
Try with:
$input = 'node/95/pdf/1';
$parts = explode('/', $input);
$output = (int) $parts[3];
OK, so there is a page I'm querying on another server that returns a comma separated list of two values. Something it would return would be:
850,640
I have some PHP code that calls file_get_contents on that page and needs to do some numeric calculations based on the two values.
No matter what I try, I can't seem to get an int value out of this.
$res = trim(file_get_contents('http://thatURL/'));
echo "X" . $res . "X<br/>";
list($x,$y) = array_map(create_function('$a', 'return (int)$a;'), explode(',', $res));
echo "X:$x";
results in the output:
X 850,640 X
X:0
Note the spaces before and after the comma separated values(how the hell? I trim'd them!) and that $x is assigned the value 0.
What am I doing wrong here?
What am I doing wrong here?
Nothing, as far as I can see, which indicates that the content of $res is not quite what you expect. Could you change the first echo to:
echo htmlentities($res);
My guess is $res contains some un-printed characters, for example, it is actually:
<span> </span>850,640<span> </span>
or
850,640
Try the following. The array_map and llamda function are arguably overkill for your usage.
$res = " 850,640 ";
echo "X" . $res . "X<br/>";
list($x,$y) = explode(',', trim($res));
echo "X:" . (int)$x;
echo "Y:" . (int)$y;
Worked for me, but I'm not using file_get_contents(). If that doesn't work, something else is being output by the page.
PHP is not a typed language. Use intval to convert a string to integer.
Correction: it is a loosely typed language! That's what I meant!
Since I was using file_get_contents() on a URL, there was some HTML being put in as well that I didn't notice in my echo because it parsed out... just empty body and html tags. Oops!
I'm trying to trim some youtube URLs that I am reading in from a playlist. The first 3 work fine and all their URLs either end in caps or numbers but this one that ends in a lower case g is getting trimmed one character shorter than the rest.
for ($z=0; $z <= 3; $z++)
{
$ythref2 = rtrim($tubeArray["feed"]["entry"][$z]["link"][0]["href"], '&feature=youtube_gdata');
The URL is http://www.youtube.com/watch?v=CuE88oVCVjg&feature=youtube_gdata .. and it should get trimmed down to .. http://www.youtube.com/watch?v=CuE88oVCVjg but instead it is coming out as http://www.youtube.com/watch?v=CuE88oVCVj.
I think it may be the ampersand symbol but I am not sure.
The second argument to rtrim is a list of characters to remove, not a string to remove.
You might want to use str_replace, or use parse_url and parse_str to get arrays of the components of the URL and the components of the query string, like "v".
Untested example code:
$youtube_url = 'http://www.youtube.com/watch?v=CuE88oVCVjg&feature=youtube_gdata';
$url_bits = parse_url($youtube_url);
$query_string = array();
parse_str($url_bits['query'], $query_string);
$video_identifier = $query_string['v']; // "CuE88oVCVjg"
$rebuilt_url = 'http://www.youtube.com/watch?v=' . $video_identifier;
No, it's the g in the second argument. rtrim() does not remove a string from the end, it removes any characters given in the second argument. Use preg_replace() or substr() instead.