php urlencode for linkedin - php

Apparently Linkedin is funny about urlencoding the ~ in https://api.linkedin.com/v1/people/~
my problem is that i use an oauth library so I need to keep things consistent.
is there a way to urlencode just part of the string so in case i have the ~ i can leave that out and put it back in at the same spot after encoding?
thank you

Use rtrim() to remove ~ and then again append it:
<?php
$URL = 'https://api.linkedin.com/v1/people/~';
echo urlencode( rtrim ( $URL, '~' ) ) . '~';
?>
This outputs:
https%3A%2F%2Fapi.linkedin.com%2Fv1%2Fpeople%2F~
[EDIT]: After OP Clarification: If there are ~ in the middle somewhere
Use str_replace to put back the character ~:
<?php
$URL = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name';
echo str_replace('%7E','~',urlencode($URL));
?>
This outputs:
https%3A%2F%2Fapi.linkedin.com%2Fv1%2Fpeople%2F~%3A%28id%2Cfirst-name%2Clast-name

Encode the string, then decode the sequence only for the ~. If you want, you may define a constant that holds the URL-encoded value for that character and replace it.
define('TILDE_URLENCODE', urlencode('~')); // Or '%7E'
$url = str_replace(TILDE_URLENCODE, '~', urlencode($url));

Related

how change part of url by preg_replace?

I am trying to change all the links of a html with php preg_replace. All the uris have the following form
test.com/item/16
I want to change it to:
test.com/z/item/16
I tried the following, but it returns no changes:
$links = 'http://test.com/item/16';
preg_replace("/item","z/item",$links);
echo $links;
// output >>> http://test.com/z/item/16
You have to use delimiters as #nickb has pointed out, i.e. /your_regular_expression/. The / is the standard delimiter for regular expressions, and so, it being a special character, you'd have to escape the / you want to match by using a backslash, \/:
preg_replace("/\/item/","z/item",$links);
But luckily, you can choose your own delimiters, like #, so then no need to escape the /:
preg_replace("#/item#","z/item",$links);
Do this:
<?php
$links = 'http://test.com/item/16';
$a = preg_replace("/item/","z/item",$links);
echo $a;
preg_replace does not change the input string but instead returns a modified string....which is stored in $a variable..
You need delimiter and return of preg_replace set to variable
$links = 'http://test.com/item/16';
$links = preg_replace('/\/item/','/z/item',$links);
echo $links;
But, why don't you use just str_replace in this case?
The problem with the provided answers is that if you have more than one instance of /item in the URL, all of them will get replaced, for example a URL like:
http://items.domain.com/item/16
would get messed up, try modifying just the path:
$path = parse_url( $url, PHP_URL_PATH );
$url = str_replace( $path, '/z'.$path, $url );

String replace with wildcard

I have a string http://localhost:9000/category that I want to replace with category.html, i.e. strip everything before /category and add .html.
But can't find a way to do this with str_replace.
You want to use parse_url in this case:
$parts = parse_url($url);
$file = $parts['path'].'.html';
Or something along that line. Experiment a bit with it.
Ismael Miguel suggested this shorter version, and I like it:
$file = parse_url($url,PHP_URL_PATH).'.html';
Much better than a ^*!$(\*)+ regular expression.
.*\/(\S+)
Try this.Replace by $1.html.see demo .
http://regex101.com/r/nA6hN9/43
Use preg_replace instead of str_replace
Regex:
.*\/(.+)
Replacement string:
$1.html
DEMO
$input = "http://localhost:9000/category";
echo preg_replace("~.*/(.+)~", '$1.html', $input)
Output:
category.html
A solution without regex:
<?php
$url = 'http://localhost:9000/category';
echo #end(explode('/',$url)).'.html';
?>
This splits the string and gets the last part, and appends .html.
Note that this won't work if the input ends with / (e.g.: $url = 'http://localhost:9000/category/';)
Also note that this relies on non-standard behavior and can be easily changed, this was just made as a one-liner. You can make $parts=explode([...]); echo end($parts).'.html'; instead.
If the input ends with / occasionally, we can do like this, to avoid problems:
<?php
$url = 'http://localhost:9000/category/';
echo #end(explode('/',rtrim($url,'/'))).'.html';
?>

How to remove escaped forward slash using php?

I am using the Google Drive API and the refresh_token I obtain has an escaped forward slash. While this should be valid JSON, the API won't accept it when calling refreshToken(). I am trying to remove the backslash using preg_replace:
$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = preg_replace('/\\\//', '/', $access_token);
I would like the returned string to be:
"1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
I've tried various expressions, but it either doesn't remove the backslash or it returns an empty string. Note that I don't want to remove all backslashes, only the ones escaping a forward slash.
Avoid regex and just use str_replace:
$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = str_replace( '\/', '/', $access_token );
//=> 1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8
Well, there's a standard function that does just that: stripslashes
So please avoid regex, str_replace et al.
It's as simple as it takes:
$access_token = stripslashes($access_token);
You can use a different delimiter. Here I chose to use the ~ as a delimiter instead of the /.
$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = preg_replace('~\\\/~', '/', $access_token);
print $access_token;
This returns:
1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8
<?php
$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
echo str_replace("\\","",$access_token);
?>
Output:
1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8
This will work for you:
$access_token = preg_replace('|\\\\|', '', $access_token);
What should happen to a string like this 1\\/Mg\otw\\\/Btow ?
If your string uses double quote interpolated escapes, then a simple find \/ replace / won't work.
You have to use this for a specific non-\ escaped char: '~(?<!\\\)((?:\\\\\\\)*)\\\(/)~'
Find - (?<!\\)((?:\\\\)*)\\(/)
Replace - $1$2
This works for me (uses negative forward lookahead):
$pattern = "/(?!\/)[\w\s]+/"
preg_match($pattern, $this->name,$matches)
$this->name = $matches[0]
name before:
WOLVERINE WORLD WIDE INC /DE/
name after:
WOLVERINE WORLD WIDE INC DE

Urlencode everything but slashes?

Is there any clean and easy way to urlencode() an arbitrary string but leave slashes (/) alone?
Split by /
urlencode() each part
Join with /
You can do like this:
$url = "http://www.google.com/myprofile/id/1001";
$encoded_url = urlencode($url);
$after_encoded_url = str_replace("%2F", "/", $url);
Basically what #clovecooks said, but split() is deprecated as of 5.3:
$path = '/path with some/illegal/characters.html';
$parsedPath = implode('/', array_map(function ($v) {
return rawurlencode($v);
}, explode('/', $path)));
// $parsedPath == '/path%20with%20some/illegal/characters.html';
Also might want to decode before encoding, in case the string is already encoded.
I suppose you are trying to encode a whole HTTP url.
I think the best solution to encode a whole HTTP url is to follow the browser strickly.
If you just skip slashes, then you will get double-encode issue if the url has already been encoded.
And if there are some parameters in the url, (?, &, =, # are in the url) the encoding will break the link.
The browsers only encode , ", <, >, ` and multi-byte characters. (Copy all symbols to the browser, you will get the list)
You only need to encode these characters.
echo preg_replace_callback("/[\ \"<>`\\x{0080}-\\x{FFFF}]+/u", function ($match) {
return rawurlencode($match[0]);
}, $path);
Yes, by properly escaping the individual parts before assembling them with slashes:
$url = urlencode($foo) . '/' . urlencode($bar) . '/' . urlencode($baz);
$encoded = implode("/", array_map(function($v) { return urlencode($v); }, split("/", $url)));
This will split the string, encode the parts and join the string together again.

Get vine video id using php

I need to get the vine video id from the url
so the output from link like this
https://vine.co/v/bXidIgMnIPJ
be like this
bXidIgMnIPJ
I tried to use code form other question here for Vimeo (NOT VINE)
Get img thumbnails from Vimeo?
This what I tried to use but I did not succeed
$url = 'https://vine.co/v/bXidIgMnIPJ';
preg_replace('~^https://(?:www\.)?vine\.co/(?:clip:)?(\d+)~','$1',$url)
basename maybe?
<?php
$url = 'https://vine.co/v/bXidIgMnIPJ';
var_dump(basename($url));
http://codepad.org/vZiFP27y
Assuming it will always be in that format, you can just split the url by the / delimiter. Regex is not needed for a simple url such as this.
$id = end(explode('/', $url));
Referring to as the question is asked here is a solution for preg_replace:
$s = 'https://vine.co/v/bXidIgMnIPJ';
$new_s = preg_replace('/^.*\//','',$s);
echo $new_s;
// => bXidIgMnIPJ
or if you need to validate that an input string is indeed a link to vine.co :
$new_s = preg_replace('/^(https?:\/\/)?(www\.)?vine\.co.*\//','',$s);
I don't know if that /v/ part is always present or is it always v... if it is then it may also be added to regex for stricter validation:
$new_s = preg_replace('/^(https?:\/\/)?(www\.)?vine\.co\/v\//','',$s);
Here's what I am using:
function getVineId($url) {
preg_match("#(?<=vine.co/v/)[0-9A-Za-z]+#", $url, $matches);
if (isset($matches[0])) {
return $matches[0];
}
return false;
}
I used a look-behind to ensure "vine.co/v/" always precedes the ID, while ignoring if the url is HTTP or HTTPS (or if it lacks a protocol altogether). It assumes the ID is alphanumeric, of any length. It will ignore any characters or parameters after the id (like Google campaign tracking parameters, etc).
I used the "#" delimiter so I wouldn't have to escape the forward slashes (/), for a cleaner look.
explode the string with '/' and the last string is what you are looking for :) Code:
$vars = explode("/",$url);
echo $vars[count($vars)-1];
$url = 'https://vine.co/v/b2PFre2auF5';
$regex = '/^http(?:s?):\/\/(?:www\.)?vine\.co\/v\/([a-zA-Z0-9]{1,13})$/';
preg_match($regex,$url,$m);
print_r($m);
1. b2PFre2auF5

Categories