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
Related
I want to replace my last \ with / on this URL string
C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm
I have tried this link, but no changes, I am missing something, please correct me where I am wrong.
Here is a solution using PHP's string functions instead of regex.
Do this:
$url = 'C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm';
$pos = strrpos($url, '\\');
$url = substr_replace($url, '/', $pos, 1);
echo $url;
To get this:
C:\wamp\www\chm-lib\sekhelp_out\HTML/AS_BUILD.htm
Explanation:
Get the position of the last \ in the input string using strrpos()
Replace that with / using substr_replace()
Note
It is important to pass '\\' instead of '\' to strrpos() as the first \ escapes the second.
Also note that you can shorten the code above to a single line if you prefer, but I thought it would be easier to understand as is. Anyway, here is the code as a one-liner function:
function reverseLastBackslash($url) {
return substr_replace($url, '/', strrpos($url, '\\'), 1);
}
You can try exploding the string as an array and imploding after popping off the last part, and connecting it back with a forward slash.
$array = explode('\','C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm');
$last = array_pop($array);
$corrected = implode('\',$array) . '/' . $last;
The backslash escaping is tricky:
preg_replace('/\\\\([^\\\\]*)$/', '/$1', "C:\\wamp\\www\\chm-lib\\sekhelp_out\\HTML\\AS_BUILD.htm")
You have to escape once for the literal string and once for the regular expression so a single \ needs to be \\\\ (1 x 2 x 2)
Simply use this
str_replace('\\','/','C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm');
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
I am trying to create a regular expression to do the following (within a preg_replace)
$str = 'http://www.site.com&ID=1620';
$str = 'http://www.site.com';
How would I write a preg_replace to simply remove the &ID=1620 from the string (taking into account the ID could be variable string length
thanks in advance
You could use...
$str = preg_replace('/[?&;]ID=\d+/', '', $str);
I'm assuming this is meant to be a normal URL, hence the [?&;]. If that's the case, the & should be a ?.
If it's part of a larger list of GET params, you are probably better off using...
parse_str($str, $params);
unset($params['ID']);
$str = http_build_query($params);
I'm guessing that & is not allowed as a character in the ID attribute. In that case, you can use
$result = preg_replace('/&ID=[^&]+/', '', $subject);
or (possibly better, thanks to PaulP.R.O.):
$result = preg_replace('/[?&]ID=[^&]+/', '', $subject);
This will remove &ID= (the second version would also remove ?ID=) plus any amount of characters that follow until the next & or end of string. This approach makes sure that any following attributes will be left alone:
$str = 'http://www.site.com?spam=eggs&ID=1620&foo=bar';
will be changed into
$str = 'http://www.site.com?spam=eggs&foo=bar';
You can just use parse_url
(that is if the URL is of the form: http://something.com?id1=1&id2=2):
$url = parse_url($str);
echo "http://{$url['host]}";
I'd like to replace more than one forward slash with one forward slash.
Examples:
this/is//an//example -> this/is/an/example
///another//example//// -> /another/example/
example.com///another//example//// -> example.com/another/example/
Thanks!
EDIT: This will be used to fix URLs that have more than one forward slash.
try
preg_replace('#/+#','/',$str);
or
preg_replace('#/{2}#','/',$str);
Tips: use str_replace for such a simple replacement AS it
replace all occurrences of the search string with the replacement string
str_replace('/','/',$str);
Reference
You might want to use regex:
$modifiedString = preg_replace('|/{2,}|','/',$strToModify);
I use the {2,} instead of + to avoid replacing single '/'.
Use a regex to replace one or more /-es with /:
$string = preg_replace('#/+#', '/', $string);
I see you want to create a valid url... you might want to check out realpath, or maybe even better the snippet in the first comment:
$path = '../gallery/index/../../advent11/app/';
$pattern = '/\w+\/\.\.\//';
while(preg_match($pattern, $path)) {
$path = preg_replace($pattern, '', $path);
}
// $path == '../advent11/app/'
As you can see this also solves ../-es :)
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));